<?php
/**
 * @package		简易CMS
 * @subpackage	缓存：插件
 * @version		$Id: function_core.php 27 2012-09-23 17:39:09Z htmambo@gmail.com $
 * @author		Hoping
 * @copyright	Copyright (C) 2010 Hoping Software Studio.
 */

if (!defined('IN_JYCMS')) {
	exit('Access Denied');
}
define('CMS_FUNCTION', true);

/**
 * 生成错误报告
 *
 * @param 错误类型 $type
 * @param 错误信息 $message
 * @param 出错文件 $file
 * @param 出错行号 $line
 * @return 无
 */
function error_report($type, $message, $file = null, $line = 0, $code = '') {
    if (!(error_reporting() & $type)) {
        // This error code is not included in error_reporting
        return true;
    }
	if (E_NOTICE == $type) {
		return true;
	}
	if ($type == 2048) {
		return true;
	}
	cmsError::system_error($message);
	return false;
}

if (function_exists("set_error_handler")) {
	set_error_handler("error_report", E_ALL ^ E_NOTICE);
}

function swapclass($class1, $class2 = '') {
	static $swapc = null;
	$swapc = isset($swapc) && $swapc != $class1 ? $class1 : $class2;
	return $swapc;
}

function smd5($str) {
	return substr(md5($str), 8, 16);
}

function parseparameter($param) {
	$paramarr = array();
	$sarr = explode('/', $param);
	if (empty($sarr))
		return $paramarr;
	if (is_numeric($sarr[0]))
		$sarr = array_merge(array('uid'), $sarr);
	if (count($sarr) % 2 != 0)
		$sarr = array_slice($sarr, 0, - 1);
	for ($i = 0; $i < count($sarr); $i = $i + 2) {
		if (!empty($sarr[$i + 1]))
			$paramarr[$sarr[$i]] = addslashes(str_replace(array('/', '\\'), '', rawurldecode(stripslashes($sarr[$i + 1]))));
	}
	return $paramarr;
}

//模块
function block($thekey, $param) {
	global $_G;
	list($blocktype, $blockname ) = explode('/', $thekey);
	$retvar = !empty($paramarr['cachename']) ? $paramarr['cachename'] : $blockname;
	$blockname = 'block_' . $blockname;
	$havethekey = false;
	$needcache = 0;
	$blockfile = './source/block/' . $blocktype . '/' . $blockname . '.php';
	//缓存key
	$cachekey = smd5($param);
	$paramarr = parseparameter($param);
	if (!empty($paramarr['uid'])) {
		$uid = $paramarr['uid'];
	} elseif (!empty($paramarr['authorid'])) {
		$uid = $paramarr['authorid'];
	} else {
		$uid = 0;
	}
	if (!empty($paramarr['cachetime'])) {
		$cacheupdatetime = $paramarr['cachetime'];
	} else {
		$cacheupdatetime = 0;
		$needcache = 1; //DO NOT CACHE
	}
	if ($cacheupdatetime) {
		//获取缓存
		$cachefile = './data/cache/block/' . substr($cachekey, 0, 2) . '/' . $cachekey . '.cache.data';
		if (file_exists($cachefile)) {
			$data = '';
			cmsFS::read($cachefile, $data);
			$_G['tpl_block'][$cachekey]['value'] = $data;
			$_G['block'][$retvar] = unserialize($data);
			$_G['tpl_block'][$cachekey]['filemtime'] = filemtime($cachefile);
		}
		if (!isset($_G['tpl_block'][$cachekey])) {
			$needcache = 1; //没有缓存
		} else {
			//创建下次更新时间
			if (!empty($_G['tpl_block'][$cachekey]['filemtime'])) {
				$_G['tpl_block'][$cachekey]['updatetime'] = $_G['tpl_block'][$cachekey]['filemtime'] + $cacheupdatetime;
			}
			if ($_G['tpl_block'][$cachekey]['updatetime'] < TIMESTAMP) {
				$needcache = 2; //需要更新
			}
		}
	}
	if ($needcache) {
		$theblockarr = array();
		include_once ($blockfile);
		$block = new $blockname ();
		$theblockarr = $block->getdata('', $paramarr);
		$_G['block'][$retvar] = $theblockarr['data'];
		if($theblockarr['html']) {
			//echo $theblockarr['html'];
			$_G['block'][$retvar] = $theblockarr;
		}
		$havethekey = true;
		$_G['tpl_block'][$cachekey]['value'] = serialize($_G['block'][$retvar]);
		$_G['tpl_block'][$cachekey]['updatetime'] = $_SGLOBAL['timestamp'] + $cacheupdatetime;
	}
	if(isset($_G['block'][$retvar]['html'])){
		echo $_G['block'][$retvar]['html'];
		unset($_G['block'][$retvar]['html']);
		$_G['block'][$retvar] = $_G['block'][$retvar]['data'];
	}
	// if(!$cacheupdatetime) pre($_G, 1);
	if (!$needcache) {
		unset($_G['tpl_block'][$cachekey]);
	}
	if (!empty($paramarr['cachename'])) {
		$_G['block'][$paramarr['cachename']] = $_G['block'][$retvar];
	}
	if ($paramarr['xmlfile']) {
		if ($_G['block'][$retvar] && is_array($_G['block'][$retvar])) {
			$html = '<playlist version="1" xmlns="http://xspf.org/ns/0/">
	<trackList>
';
			foreach ($_G['block'][$retvar] as $v) {
				$html .= '		<track>
			<title>' . $v['title'] . '</title>
			<info>' . $v['url'] . '</info>
			<location>' . $v['pic'] . '</location>
		</track>
';
			}
			$html .= '	</trackList>
</playlist>';
			include_once libfile('class/files');
			cmsFS::write('./data/tmp/' . $paramarr['xmlfile'] . '.xml', $html);
		}
	}
}

function system_error($message) {
	global $mainframe;
	//如果系统尚未初始化成功，则不触发错误陷阱
	if (!$mainframe->initated)
		exit($message);

	require_once libfile('class/error');
	cmsError::system_error($message);
}

function updatesession($force = false) {
	global $_G;
	static $updated = false;
	if (IS_ROBOT)
		return true;
	if (!$updated) {
		$mainframe = & cmsCore::instance();
		foreach ($mainframe->session->var as $k => $v) {
			if (isset($_G['member'][$k]) && $k != 'lastactivity') {
				$mainframe->session->set($k, $_G['member'][$k]);
			}
		}
		$mainframe->session->update();
		$updated = true;
		if ($_G['uid'] && TIMESTAMP - $_G['member']['lastactivity'] > 21600) {
			DB::update('common_member', array('lastip' => $_G['clientip'], 'lastactivity' => TIMESTAMP, 'lastvisit' => TIMESTAMP), "uid='$_G[uid]'", 1);
		}
	}
	return $updated;
}

function dmicrotime() {
	return array_sum(explode(' ', microtime()));
}

function setglobal($key, $value, $group = null) {
	global $_G;
	$k = explode('/', $group === null ? $key : $group . '/' . $key);
	switch (count($k)) {
		case 1 :
			$_G[$k[0]] = $value;
			break;
		case 2 :
			$_G[$k[0]][$k[1]] = $value;
			break;
		case 3 :
			$_G[$k[0]][$k[1]][$k[2]] = $value;
			break;
		case 4 :
			$_G[$k[0]][$k[1]][$k[2]][$k[3]] = $value;
			break;
		case 5 :
			$_G[$k[0]][$k[1]][$k[2]][$k[3]][$k[4]] = $value;
			break;
	}
	return true;
}

function getglobal($key, $group = null) {
	global $_G;
	$k = explode('/', $group === null ? $key : $group . '/' . $key);
	switch (count($k)) {
		case 1 :
			return isset($_G[$k[0]]) ? $_G[$k[0]] : null;
			break;
		case 2 :
			return isset($_G[$k[0]][$k[1]]) ? $_G[$k[0]][$k[1]] : null;
			break;
		case 3 :
			return isset($_G[$k[0]][$k[1]][$k[2]]) ? $_G[$k[0]][$k[1]][$k[2]] : null;
			break;
		case 4 :
			return isset($_G[$k[0]][$k[1]][$k[2]][$k[3]]) ? $_G[$k[0]][$k[1]][$k[2]][$k[3]] : null;
			break;
		case 5 :
			return isset($_G[$k[0]][$k[1]][$k[2]][$k[3]][$k[4]]) ? $_G[$k[0]][$k[1]][$k[2]][$k[3]][$k[4]] : null;
			break;
	}
	return null;
}

function getgpc($k, $type = 'GP') {
	$type = strtoupper($type);
	switch ($type) {
		case 'G' :
			$var = &$_GET;
			break;
		case 'P' :
			$var = &$_POST;
			break;
		case 'C' :
			$var = &$_COOKIE;
			break;
		default :
			if (isset($_GET[$k])) {
				$var = &$_GET;
			} else {
				$var = &$_POST;
			}
			break;
	}
	return isset($var[$k]) ? $var[$k] : NULL;
}

function getuserbyuid($uid) {
	static $users = array();
	if (empty($users[$uid])) {
		$users[$uid] = DB::fetch_first("SELECT m.* FROM #__common_member m
			WHERE m.uid='$uid'");
	}
	return $users[$uid];
}

function daddslashes($string, $force = 1) {
	if (is_array($string)) {
		foreach ($string as $key => $val) {
			unset($string[$key]);
			$string[addslashes($key)] = daddslashes($val, $force);
		}
	} else {
		$string = addslashes($string);
	}
	return $string;
}

function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {
	$ckey_length = 4;
	$key = md5($key != '' ? $key : getglobal('authkey'));
	$keya = md5(substr($key, 0, 16));
	$keyb = md5(substr($key, 16, 16));
	$keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length) : substr(md5(microtime()), - $ckey_length)) : '';
	$cryptkey = $keya . md5($keya . $keyc);
	$key_length = strlen($cryptkey);
	$string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0) . substr(md5($string . $keyb), 0, 16) . $string;
	$string_length = strlen($string);
	$result = '';
	$box = range(0, 255);
	$rndkey = array();
	for ($i = 0; $i <= 255; $i++) {
		$rndkey[$i] = ord($cryptkey[$i % $key_length]);
	}
	for ($j = $i = 0; $i < 256; $i++) {
		$j = ($j + $box[$i] + $rndkey[$i]) % 256;
		$tmp = $box[$i];
		$box[$i] = $box[$j];
		$box[$j] = $tmp;
	}
	for ($a = $j = $i = 0; $i < $string_length; $i++) {
		$a = ($a + 1) % 256;
		$j = ($j + $box[$a]) % 256;
		$tmp = $box[$a];
		$box[$a] = $box[$j];
		$box[$j] = $tmp;
		$result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
	}
	if ($operation == 'DECODE') {
		if ((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26) . $keyb), 0, 16)) {
			return substr($result, 26);
		} else {
			return '';
		}
	} else {
		return $keyc . str_replace('=', '', base64_encode($result));
	}
}

function dfsockopen($url, $limit = 0, $post = '', $cookie = '', $bysocket = FALSE, $ip = '', $timeout = 15, $block = TRUE) {
	$return = '';
	$matches = parse_url($url);
	$host = $matches['host'];
	$path = $matches['path'] ? $matches['path'] . ($matches['query'] ? '?' . $matches['query'] : '') : '/';
	$port = !empty($matches['port']) ? $matches['port'] : 80;
	if ($post) {
		$out = "POST $path HTTP/1.0\r\n";
		$out .= "Accept: */*\r\n";
		$out .= "Accept-Language: zh-cn\r\n";
		$out .= "Content-Type: application/x-www-form-urlencoded\r\n";
		$out .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n";
		$out .= "Host: $host\r\n";
		$out .= 'Content-Length: ' . strlen($post) . "\r\n";
		$out .= "Connection: Close\r\n";
		$out .= "Cache-Control: no-cache\r\n";
		$out .= "Cookie: $cookie\r\n\r\n";
		$out .= $post;
	} else {
		$out = "GET $path HTTP/1.0\r\n";
		$out .= "Accept: */*\r\n";
		$out .= "Accept-Language: zh-cn\r\n";
		$out .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n";
		$out .= "Host: $host\r\n";
		$out .= "Connection: Close\r\n";
		$out .= "Cookie: $cookie\r\n\r\n";
	}
	$fp = @fsockopen(($ip ? $ip : $host), $port, $errno, $errstr, $timeout);
	if (!$fp) {
		return '';
	} else {
		stream_set_blocking($fp, $block);
		stream_set_timeout($fp, $timeout);
		@fwrite($fp, $out);
		$status = stream_get_meta_data($fp);
		if (!$status['timed_out']) {
			while (!feof($fp)) {
				if (($header = @fgets($fp)) && ($header == "\r\n" || $header == "\n")) {
					break;
				}
			}
			$stop = false;
			while (!feof($fp) && !$stop) {
				$data = fread($fp, ($limit == 0 || $limit > 8192 ? 8192 : $limit));
				$return .= $data;
				if ($limit) {
					$limit -= strlen($data);
					$stop = $limit <= 0;
				}
			}
		}
		@fclose($fp);
		return $return;
	}
}

function dhtmlspecialchars($string) {
	if (is_array($string)) {
		foreach ($string as $key => $val) {
			$string[$key] = dhtmlspecialchars($val);
		}
	} else {
		$string = preg_replace('/&amp;((#(\d{3,5}|x[a-fA-F0-9]{4}));)/', '&\\1', str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $string));
	}
	return $string;
}

function dexit($message = '') {
	echo $message;
	output();
	exit();
}

function dheader($string, $replace = true, $http_response_code = 0) {
	$string = str_replace(array("\r", "\n"), array('', ''), $string);
	if (empty($http_response_code) || PHP_VERSION < '4.3') {
		@header($string, $replace);
	} else {
		@header($string, $replace, $http_response_code);
	}
	if (preg_match('/^\s*location:/is', $string)) {
		exit();
	}
}

/**
 * 设置COOKIE
 *
 * @param string $var COOKIE变量
 * @param string $value 值
 * @param int $life COOKIE保存时间
 * @param string $prefix COOKIE变量前缀
 * @param unknown_type $httponly
 */
function dsetcookie($var, $value = '', $life = 0, $prefix = 1, $httponly = false) {
	global $_G;
	$config = $_G['config']['cookie'];
	$_G['cookie'][$var] = $value;
	$var = ($prefix ? $config['cookiepre'] : '') . $var;
	$_COOKIE[$var] = $var;
	if ($value == '' || $life < 0) {
		$value = '';
		$life = - 1;
	}
	$life = $life > 0 ? getglobal('timestamp') + $life : ($life < 0 ? getglobal('timestamp') - 31536000 : 0);
	$path = $httponly && PHP_VERSION < '5.2.0' ? $config['cookiepath'] . '; HttpOnly' : $config['cookiepath'];
	$secure = $_SERVER['SERVER_PORT'] == 443 ? 1 : 0;
	if (PHP_VERSION < '5.2.0') {
		setcookie($var, $value, $life, $path, $config['cookiedomain'], $secure);
	} else {
		setcookie($var, $value, $life, $path, $config['cookiedomain'], $secure, $httponly);
	}
}

function fileext($filename) {
	return addslashes(trim(substr(strrchr($filename, '.'), 1, 10)));
}

/**
 * 生成表单验证HASH值
 *
 * @param string $specialadd 特定字符串
 * @return string
 */
function formhash($specialadd = '') {
	global $_G;
	$hashadd = defined('IN_ADMINCP') ? 'Only For JYCMS Admin Control Panel' : '';
	return substr(md5(substr($_G['timestamp'], 0, - 7) . $_G['username'] . $_G['uid'] . $_G['authkey'] . $hashadd . $specialadd), 8, 8);
}

/**
 * 检测来访是否为搜索引擎蜘蛛
 *
 * @param string $useragent 来访标志
 * @return boolean
 */
function checkrobot($useragent = '') {
	static $kw_spiders = 'Bot|Crawl|Spider|slurp|sohu-search|lycos|robozilla';
	static $kw_browsers = 'MSIE|Netscape|Opera|Konqueror|Mozilla';
	$useragent = empty($useragent) ? $_SERVER['HTTP_USER_AGENT'] : $useragent;
	if (!strexists($useragent, 'http://') && preg_match("/($kw_browsers)/i", $useragent)) {
		return false;
	} elseif (preg_match("/($kw_spiders)/i", $useragent)) {
		return true;
	} else {
		return false;
	}
}

/**
 * 记录来访的蜘蛛
 *
 * @return unknown
 */
function robotlog() {
	global $_G, $db;
	$useragent = $_SERVER['HTTP_USER_AGENT'];
	$remoteaddr = $_G['clientip'];
	$timestamp = $_G['timestamp'];
	$tdate = date("Y-m-d", $timestamp);
	$regex = "(!:[\\/\\-]?\\d+(\\.\\d+)+)?";
	$regex = "/[a-z\\s!]*?[\\w\\-]*(?:Bot|Spider|Twiceler|Crawl|ia_archiver|Slurp|ZyBorg|MSIECrawler|UdmSearch|IRLbo)[a-z\\-]*[a-z\\s]*{$regex}/i";
	preg_match($regex, $useragent, $matches);
	if ($matches == false) {
		return false;
	}
	$robotName = trim($matches[0], " \\-");
	if (empty($db))
		$db = & DB::object();
	$remoteaddr = $_SERVER['REMOTE_ADDR'];
	$timestamp = time();
	$sql = "UPDATE #__spider SET `times`=`times`+1, `last_visit`='" . $timestamp . "' where `name`='{$robotName}'";
	$query = DB::query($sql, "SKIP_ERROR");
	$result = DB::affected_rows($query);
	if ($result < 1) {
		$sql = "REPLACE into #__spider (`name`,`times`,`first_visit`,`last_visit`,`agent`) values('{$robotName}','1','{$timestamp}','{$timestamp}','{$useragent}')";
		$query = DB::query($sql);
		$result = DB::affected_rows($query);
	}
	if ($result) {
		$sql = "UPDATE #__spider_ip set `times`=`times`+1, `last_visit`='{$timestamp}' where `ip`='{$remoteaddr}'";
		$query = DB::query($sql, "SKIP_ERROR");
		$result = DB::affected_rows($query);
		if ($result < 1) {
			$sql = "insert into #__spider_ip (`ip`,`name`,`times`,`first_visit`,`last_visit`) values('{$remoteaddr}','{$robotName}','1','{$timestamp}','{$timestamp}')";
			$query = DB::query($sql);
			$result = DB::affected_rows($query);
		}
	}
	$sql = "UPDATE #__spider_log SET `times`=`times`+1, `last_visit`=" . $timestamp . " WHERE `name`='{$robotName}' and `date`='{$tdate}'";
	$query = DB::query($sql, "SKIP_ERROR");
	$result = DB::affected_rows($query);
	if (0 < $result) {
		return true;
	}
	$sql = "INSERT INTO #__spider_log (`name`,`times`,`date`,`first_visit`,`last_visit`) VALUES ('{$robotName}','1','{$tdate}','{$timestamp}','{$timestamp}')";
	$result = DB::query($sql);
	return $result;
}

function isemail($email) {
	return strlen($email) > 6 && preg_match("/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/", $email);
}

function quescrypt($questionid, $answer) {
	return $questionid > 0 && $answer != '' ? substr(md5($answer . md5($questionid)), 16, 8) : '';
}

function random($length, $numeric = 0) {
	$seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
	$seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
	$hash = '';
	$max = strlen($seed) - 1;
	for ($i = 0; $i < $length; $i++) {
		$hash .= $seed{mt_rand(0, $max)};
	}
	return $hash;
}

function strexists($string, $find) {
	return !(strpos($string, $find) === FALSE);
}

function avatar($uid, $size = 'middle', $returnsrc = FALSE, $real = FALSE, $static = FALSE) {
	global $_G;
	$size = in_array($size, array('big', 'middle', 'small')) ? $size : 'middle';
	$img = STATICURL . 'image/common/noavatar_' . $size . '.gif';
	return '<img src="' . $img . '" />';
}

function lang($file, $langvar = null, $vars = array(), $default = null) {
	global $_G, $cmsLang;
	list($path, $file ) = explode('/', $file);
	if (!$file) {
		$file = $path;
		$path = '';
	}
	if (!empty($cmsLang)) {
		if ($path)
			$lf = $path . '_' . $file;
		else
			$lf = $file;
		if (substr($lf, 0, 5) == 'admin') {
			$cmsLang->load('admin');
		} else {
			if($langvar && !$cmsLang->haskey($langvar))
			$cmsLang->load($file);
		}
	}
	if (!empty($cmsLang) && $langvar && $cmsLang->haskey($langvar)) {
		$return = $cmsLang->_($langvar);
	} else {
		$key = $path == '' ? $file : $path . '_' . $file;
		if (!isset($_G['lang'][$key])) {
			@include ROOT_PATH . './source/language/' . ($path == '' ? '' : $path . '/') . 'lang_' . $file . '.php';
			$_G['lang'][$key] = $lang;
		}
		$returnvalue = &$_G['lang'];
		$return = $langvar !== null ? (isset($returnvalue[$key][$langvar]) ? $returnvalue[$key][$langvar] : null) : $returnvalue[$key];
		$return = $return === null ? ($default !== null ? $default : $langvar) : $return;
		if (!empty($cmsLang)) {
			if ($langvar) {
				if (!$cmsLang->haskey($langvar)) {
					if (is_array($return)) {
						$trans = anytypetostring($return);
					} else {
						$trans = $return;
					}
					$cmsLang->addstr($langvar, $trans);
				}
			}
		}
	}
	if ($vars && is_array($vars)) {
		$searchs = $replaces = array();
		foreach ($vars as $k => $v) {
			$searchs[] = '{' . $k . '}';
			$replaces[] = $v;
		}
		$return = str_replace($searchs, $replaces, $return);
	}
	if(is_array($return)){
		$return = anytypetostring($return);
		//pre($return , 1);
	}
	if ($return && is_string($return) && @strpos($return, '{$') !== false) {
		//要直接在语言包中使用变量的话，要求该变量必须是全局变量
		unset($searchs, $replaces);
		$regex = '@\{(\$[^\}]+)\}@i';
		@preg_match_all($regex, $return, $match);
		if ($match[1]) {
			foreach ($match[0] as $k => $v) {
				$searchs[] = $v;
				$v = $match[1][$k];
				if (!strpos($v, '[')) {
					$v = str_replace('$', '', $v);
					$v = $GLOBALS[$v];
				} else
					$v = eval("return $v;");
				$replaces[] = $v;
			}
			$return = str_replace($searchs, $replaces, $return);
		}
	}
	return $return;
}

function checktplrefresh($maintpl, $subtpl, $timecompare, $templateid, $cachefile, $tpldir, $file) {
	static $tplrefresh, $timestamp;
	if ($tplrefresh === null) {
		$tplrefresh = getglobal('config/output/tplrefresh');
		$timestamp = getglobal('timestamp');
	}
	if (empty($timecompare) || $tplrefresh == 1 || ($tplrefresh > 1 && !($timestamp % $tplrefresh))) {
		if (empty($timecompare) || @filemtime(ROOT_PATH . $subtpl) > $timecompare) {
			@require_once(ROOT_PATH . '/source/class/class_template.php');
			$template = new template ();
			$template->parse_template($maintpl, $templateid, $tpldir, $file, $cachefile);
			return TRUE;
		}
	}
	return FALSE;
}

function template($file, $templateid = 0, $tpldir = '', $gettplfile = 0, $primaltpl = '') {
	global $_G, $cmsLang;
	static $_init_style = false;
	if ($_init_style === false) {
		$mainframe = & cmsCore::instance();
		$mainframe->_init_style();
		$_init_style = true;
	}
	if (strexists($file, ':')) {
		$clonefile = '';
		list($templateid, $file, $clonefile ) = explode(':', $file);
		$oldfile = $file;
		$file = empty($clonefile) || STYLEID != $_G['cache']['style_default']['styleid'] ? $file : $file . '_' . $clonefile;
		if ($templateid == 'diy' && STYLEID == $_G['cache']['style_default']['styleid']) {
			$_G['style']['prefile'] = '';
			$diypath = ROOT_PATH . './data/diy/';
			$preend = '_diy_preview';
			$previewname = $diypath . $file . $preend . '.htm';
			$_G['gp_preview'] = !empty($_G['gp_preview']) ? $_G['gp_preview'] : '';
			$curtplname = $oldfile;
			if (file_exists($diypath . $file . '.htm')) {
				$tpldir = 'data/diy';
				!$gettplfile && $_G['style']['tplsavemod'] = 1;
				$curtplname = $file;
				$flag = file_exists($previewname);
				if ($_G['gp_preview'] == 'yes') {
					$file .= $flag ? $preend : '';
				} else {
					$_G['style']['prefile'] = $flag ? 1 : '';
				}
			} elseif (file_exists($diypath . ($primaltpl ? $primaltpl : $oldfile) . '.htm')) {
				$file = $primaltpl ? $primaltpl : $oldfile;
				$tpldir = 'data/diy';
				!$gettplfile && $_G['style']['tplsavemod'] = 0;
				$curtplname = $file;
				$flag = file_exists($previewname);
				if ($_G['gp_preview'] == 'yes') {
					$file .= $flag ? $preend : '';
				} else {
					$_G['style']['prefile'] = $flag ? 1 : '';
				}
			} else {
				$file = $primaltpl ? $primaltpl : $oldfile;
			}
			$tplrefresh = $_G['config']['output']['tplrefresh'];
			$tplmtime = @filemtime($diypath . $file . '.htm');
			if ($tpldir == 'data/diy' && ($tplrefresh == 1 || ($tplrefresh > 1 && !($_G['timestamp'] % $tplrefresh))) && $tplmtime && $tplmtime < @filemtime(ROOT_PATH . TPLDIR . '/' . ($primaltpl ? $primaltpl : $oldfile) . '.htm')) {
				if (!updatediytemplate($file)) {
					@unlink($diypath . $file . '.htm');
					$tpldir = '';
				}
			}
			if (!$gettplfile && empty($_G['style']['tplfile'])) {
				$_G['style']['tplfile'] = empty($clonefile) ? $curtplname : $oldfile . ':' . $clonefile;
			}
			$_G['style']['prefile'] = !empty($_G['gp_preview']) && $_G['gp_preview'] == 'yes' ? '' : $_G['style']['prefile'];
		}
	}
	$file .=!empty($_G['inajax']) && ($file == 'common/header' || $file == 'common/footer') ? '_ajax' : '';
	$tpldir = $tpldir ? $tpldir : (defined('TPLDIR') ? TPLDIR : '');
	$templateid = $templateid ? $templateid : (defined('TEMPLATEID') ? TEMPLATEID : '');
	$tplfile = ($tpldir ? $tpldir . '/' : './template/') . $file . '.htm';
	$filebak = $file;
	//echo $tplfile.'<br>';
	$file == 'common/header' && defined('CURMODULE') && CURMODULE && $file = 'common/header_' . $_G['basescript'] . '_' . CURMODULE;
	$cachefile = './data/template/' . (defined('STYLEID') ? STYLEID . '_' : '_') . $templateid . '_' . str_replace('/', '_', $file) . '.tpl.php';
	if ($templateid != 1 && !@file_exists(ROOT_PATH . $tplfile)) {
		$tplfile = './template/default/' . $filebak . '.htm';
	}
	if ($gettplfile) {
		return $tplfile;
	}
	checktplrefresh($tplfile, $tplfile, @filemtime(ROOT_PATH . $cachefile), $templateid, $cachefile, $tpldir, $file);
	return ROOT_PATH . $cachefile;
}

function modauthkey($id) {
	global $_G;
	return md5($_G['username'] . $_G['uid'] . $_G['authkey'] . substr(TIMESTAMP, 0, - 7) . $id);
}

function getcurrentnav() {
	global $_G;
	if (!empty($_G['mnid'])) {
		return $_G['mnid'];
	}
	$mnid = '';
	$_G['basefilename'] = $_G['basefilename'] == $_G['basescript'] ? $_G['basefilename'] : $_G['basescript'] . '.php';
	if ($_G['setting']['navmns'] && $_G['basefilename'])
		if (array_key_exists($_G['basefilename'], $_G['setting']['navmns'])) {
			foreach ($_G['setting']['navmns'][$_G['basefilename']] as $navmn) {
				if ($navmn[0] == array_intersect_assoc($navmn[0], $_GET)) {
					$mnid = $navmn[1];
				}
			}
		}
	if (!$mnid && isset($_G['setting']['navdms'])) {
		foreach ($_G['setting']['navdms'] as $navdm => $navid) {
			if (strexists(strtolower($_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']), $navdm)) {
				$mnid = $navid;
				break;
			}
		}
	}
	if (!$mnid && isset($_G['setting']['navmn'][$_G['basefilename']])) {
		$mnid = $_G['setting']['navmn'][$_G['basefilename']];
	}
	if (!$mnid) {
		$tid = 0;
		$option = $_G['gp_option'];
		$task = $_G['gp_task'];
		$id = $_G['gp_id'];
		$url = 'index.php';
		if ($option) {
			$url .= '?option=' . $option;
			$ourl = $url;
		}
		if ($task) {
			if ($option)
				$url .= '&';
			else
				$url .= '?';
			$url .= 'task=' . $task;
			$turl = $url;
		}
		if ($id) {
			if ($option || $task)
				$url .= '&';
			else
				$url .= '?';
			$url .= 'id=' . $id;
			$iurl = $url;
		}
		//echo $url."<br>\r\n";
		foreach ($_G['setting']['navs'] as $id => $nav) {
			$navdm = $nav['filename'];
			$navid = $nav['navid'];
			//echo $navdm."<br>\r\n";
			if (strtolower($url) == $navdm) {
				$mnid = $navid;
				break;
			}
			if (strtolower($ourl) == $navdm) {
				$omnid = $navid;
			}
			if (strtolower($turl) == $navdm) {
				$tmnid = $navid;
			}
			if (strtolower($iurl) == $navdm) {
				$imnid = $navid;
				break;
			}
		}
		if (!$mnid) {
			if ($imnid)
				$mnid = $imnid;
			elseif ($tmnid)
				$mnid = $tmnid;
			elseif ($omnid)
				$mnid = $omnid;
		}
	}
	//echo $mnid;
	if (!$mnid)
		$mnid = 'mn_index';
	return $mnid;
}

/**
 * 加载系统缓存
 * @global array $_G 系统全局变量
 * @staticvar array $loadedcache 当前已经加载过的缓存信息
 * @param array $cachenames 要加载的缓存项目 （组）
 * @param boolean $force 是否强制重新加载
 * @return boolean 是否加载成功
 */
function loadcache($cachenames, $force = false) {
	global $_G;
	static $loadedcache = array();
	$cachenames = is_array($cachenames) ? $cachenames : array($cachenames);
	$caches = array();
	foreach ($cachenames as $k) {
		if (!isset($loadedcache[$k]) || $force) {
			$caches[] = $k;
			$loadedcache[$k] = true;
		}
	}
	if (!empty($caches)) {
		$cachedata = cachedata($caches);
		foreach ($cachedata as $cname => $data) {
			if (!$data) {
				include_once libfile('function/cache');
				updatecache($cname);
				continue;
			}
			if ($cname == 'setting') {
				$_G['setting'] = $data;
			} elseif (strexists($cname, 'usergroup_' . $_G['groupid']) && $_G['groupid']) {
				$_G['cache'][$cname] = $_G['perm'] = $_G['group'] = $data;
			} elseif (!$_G['uid'] && strexists($cname, 'usergroup_10')) { //新注册用户组ID
				$_G['perm'] = $data;
			} elseif ($cname == 'style_default') {
				$_G['cache'][$cname] = $_G['style'] = $data;
			} elseif ($cname == 'grouplevels') {
				$_G['grouplevels'] = $data;
			} else {
				$_G['cache'][$cname] = $data;
			}
		}
	}
	return true;
}

function cachedata($cachenames) {
	global $_G;
	$data = array();
	$cachenames = is_array($cachenames) ? $cachenames : array($cachenames);
	$lostcaches = array();
	foreach ($cachenames as $cachename) {
		if (!@include_once (ROOT_PATH . './data/cache/cache_' . $cachename . '.php')) {
			$lostcaches[] = $cachename;
		}
	}
	if (!$lostcaches) {
		return $data;
	}
	$cachenames = $lostcaches;
	unset($lostcaches);
	foreach ($cachenames as $name) {
		if ($data[$name] === null) {
			$data[$name] = null;
		}
	}
	return $data;
}

function dgmdate($timestamp, $format = 'dt', $timeoffset = '9999', $uformat = '') {
	global $_G;
	$format == 'u' && !$_G['setting']['dateconvert'] && $format = 'dt';
	static $dformat, $tformat, $dtformat, $offset, $lang;
	if ($dformat === null) {
		$dformat = getglobal('setting/dateformat');
		$tformat = getglobal('setting/timeformat');
		$dtformat = $dformat . ' ' . $tformat;
		$offset = getglobal('member/timeoffset');
		$lang = lang('core', 'date');
	}
	$timeoffset = $timeoffset == 9999 ? $offset : $timeoffset;
	$timestamp += $timeoffset * 3600;
	$format = empty($format) || $format == 'dt' ? $dtformat : ($format == 'd' ? $dformat : ($format == 't' ? $tformat : $format));
	if ($format == 'u') {
		$todaytimestamp = TIMESTAMP - (TIMESTAMP + $timeoffset * 3600) % 86400 + $timeoffset * 3600;
		$s = gmdate(!$uformat ? $dtformat : $uformat, $timestamp);
		$time = TIMESTAMP + $timeoffset * 3600 - $timestamp;
		if ($timestamp >= $todaytimestamp) {
			if ($time > 3600) {
				return '<span title="' . $s . '">' . intval($time / 3600) . '&nbsp;' . lang('core', 'hours ago') . '</span>';
			} elseif ($time > 1800) {
				return '<span title="' . $s . '">' . lang('core', 'half hour ago') . '</span>';
			} elseif ($time > 60) {
				return '<span title="' . $s . '">' . intval($time / 60) . '&nbsp;' . lang('core', 'minutes ago') . '</span>';
			} elseif ($time > 0) {
				return '<span title="' . $s . '">' . $time . '&nbsp;' . lang('core', 'seconds ago') . '</span>';
			} elseif ($time == 0) {
				return '<span title="' . $s . '">' . lang('core', 'now') . '</span>';
			} else {
				return $s;
			}
		} elseif (($days = intval(($todaytimestamp - $timestamp) / 86400)) >= 0 && $days < 7) {
			if ($days == 0) {
				return '<span title="' . $s . '">' . lang('core', 'Yesterday') . '&nbsp;' . gmdate($tformat, $timestamp) . '</span>';
			} elseif ($days == 1) {
				return '<span title="' . $s . '">' . lang('core', 'before yesterday') . '&nbsp;' . gmdate($tformat, $timestamp) . '</span>';
			} else {
				return '<span title="' . $s . '">' . ($days + 1) . '&nbsp;' . lang('core', 'days ago') . '</span>';
			}
		} else {
			return $s;
		}
	} else {
		return gmdate($format, $timestamp);
	}
}

function dmktime($date) {
	if (strpos($date, '-')) {
		$time = explode('-', $date);
		return mktime(0, 0, 0, $time[1], $time[2], $time[0]);
	}
	return 0;
}

function block_get($parameter) {
	include_once libfile('function/block');
	block_get_batch($parameter);
	return true;
}

function block_display($bid) {
	include_once libfile('function/block');
	echo block_fetch_content($bid);
}

function dimplode($array) {
	if (!empty($array)) {
		return "'" . implode("','", is_array($array) ? $array : array($array)) . "'";
	} else {
		return 0;
	}
}

function __autoload($class_name) {
	$class_name = strtolower($class_name);
	if (substr($class_name, 0, 3) == 'cms') {
		$class_name = str_replace('cms', '', strtolower($class_name));
		require_once libfile('class/' . $class_name);
	} else {
		require_once libfile('model/' . $class_name);
	}
}

function libfile($libname, $folder = '', $exit = true) {
	$libpath = './source/' . $folder;
	$fn = '';
	if (strstr($libname, '/')) {
		list($pre, $name ) = @explode('/', $libname);
		$fn = @realpath("{$libpath}/{$pre}/{$pre}_{$name}.php");
	} else {
		$fn = @realpath("{$libpath}/{$libname}.php");
	}
	if ($fn && @file_exists($fn)) {
		return $fn;
	}
	if ($exit)
		system_error($libname . " is not found!" . $fn);
}

function cutstr($string, $length, $dot = ' ...') {
	if (strlen($string) <= $length) {
		return $string;
	}
	$pre = '{%';
	$end = '%}';
	$string = str_replace(array('&amp;', '&quot;', '&lt;', '&gt;'), array($pre . '&' . $end, $pre . '"' . $end, $pre . '<' . $end, $pre . '>' . $end), $string);
	$strcut = '';
	if (strtolower(CHARSET) == 'utf-8') {
		$n = $tn = $noc = 0;
		while ($n < strlen($string)) {
			$t = ord($string[$n]);
			if ($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
				$tn = 1;
				$n++;
				$noc++;
			} elseif (194 <= $t && $t <= 223) {
				$tn = 2;
				$n += 2;
				$noc += 2;
			} elseif (224 <= $t && $t <= 239) {
				$tn = 3;
				$n += 3;
				$noc += 2;
			} elseif (240 <= $t && $t <= 247) {
				$tn = 4;
				$n += 4;
				$noc += 2;
			} elseif (248 <= $t && $t <= 251) {
				$tn = 5;
				$n += 5;
				$noc += 2;
			} elseif ($t == 252 || $t == 253) {
				$tn = 6;
				$n += 6;
				$noc += 2;
			} else {
				$n++;
			}
			if ($noc >= $length) {
				break;
			}
		}
		if ($noc > $length) {
			$n -= $tn;
		}
		$strcut = substr($string, 0, $n);
	} else {
		for ($i = 0; $i < $length; $i++) {
			$strcut .= ord($string[$i]) > 127 ? $string[$i] . $string[++$i] : $string[$i];
		}
	}
	$strcut = str_replace(array($pre . '&' . $end, $pre . '"' . $end, $pre . '<' . $end, $pre . '>' . $end), array('&amp;', '&quot;', '&lt;', '&gt;'), $strcut);
	return $strcut . $dot;
}

function dstripslashes($string) {
	if (is_array($string)) {
		foreach ($string as $key => $val) {
			$string[$key] = dstripslashes($val);
		}
	} else {
		$string = stripslashes($string);
	}
	return $string;
}

function rewritedata() {
	global $_G;
	$data = array();
	if (!defined('IN_ADMINCP')) {
		$temp = parse_url($_G['siteurl']);
		$temp = parse_url(get_domain());
		$domain = $temp['host'];
		$port = empty($_SERVER['SERVER_PORT']) || $_SERVER['SERVER_PORT'] == '80' ? '' : ':' . $_SERVER['SERVER_PORT'];
		$pregxprw = '<a href\="http\:\/\/(' . preg_quote($domain . $port . $_G['siteroot'], '/') . ')';
		if (in_array('portal_article', $_G['setting']['rewritestatus'])) {
			$data['search']['portal_article'] = "/" . $pregxprw . "index\.php\?task\=view&(amp;)?aid\=(.+?)(&amp;page\=(\d+))?\"([^\>]*)\>/e";
			$data['replace']['portal_article'] = "rewriteoutput('portal_article', 0, '\\1', '\\3', '\\5', '\\6')";
		}
		if (in_array('portal_cate', $_G['setting']['rewritestatus'])) {
			$data['search']['portal_cate'] = "/" . $pregxprw . "index\.php\?task\=list&(amp;)?catid\=(\d+)(&amp;page\=(\d+))?\"([^\>]*)\>/e";
			$data['replace']['portal_cate'] = "rewriteoutput('portal_cate', 0, '\\1', '\\3', '\\5', '\\6')";
		}
		if (in_array('all_script', $_G['setting']['rewritestatus'])) {
			$data['search']['all_script'] = "/" . $pregxprw . "index\.php([^\"]+?)\"([^\>]*)?\>/e";
			$data['replace']['all_script'] = "rewriteoutput('all_script', 0, '\\1', '\\2', '\\3')";
		}
	} else {
		$data['rulesearch']['portal_article'] = 'article/{id}:{alias}/{page}.html';
		$data['rulereplace']['portal_article'] = 'index.php?task=view&aid={id}:{alias}&page={page}';
		$data['rulevars']['portal_article']['{id}'] = '([0-9]+)';
		$data['rulevars']['portal_article']['{alias}'] = '(.+?)';
		$data['rulevars']['portal_article']['{page}'] = '([0-9]+)';
		$data['rulesearch']['portal_cate'] = 'cate/{id}:{alias}/{page}.html';
		$data['rulereplace']['portal_cate'] = 'index.php?task=list&catid={id}&page={page}';
		$data['rulevars']['portal_cate']['{id}'] = '([0-9]+)';
		$data['rulevars']['portal_cate']['{alias}'] = '(.+?)';
		$data['rulevars']['portal_cate']['{page}'] = '([0-9]+)';
		$data['rulesearch']['all_script'] = '{script}/{param}.html';
		$data['rulereplace']['all_script'] = 'index.php?rewrite={param}';
		$data['rulevars']['all_script']['{script}'] = '([a-z]+)';
		$data['rulevars']['all_script']['{param}'] = '(.+)';
	}
	return $data;
}

function rewriteoutput($type, $returntype, $host) {
	global $_G;
	$host = $host ? 'http://' . $host : '';
	$alias = $added = $fextra = '';
	if ($type == 'portal_article') {
		$id = $alias = $page = $added = '';
		@list(,,, $id, $page, $extra ) = func_get_args();
		$page = intval($page);
		  if(($id) && (intval($id)!=$id))
		  list($id, $alias ) = explode(':', $id);
		  if ($alias) {
		  list($alias, $added) = explode('#', $alias);
		  if($added) $added = '#'.$added;
		  $alias = str_replace(' ', '-', $alias);
		  $alias = str_replace('---', '-', $alias);
		  $alias = str_replace('--', '-', $alias);
		  }
		$r = array('{id}' => $id, '{alias}' => $alias, '{page}' => $page ? $page : 1);
	} elseif ($type == 'portal_cate') {
		@list(,,, $id, $page, $extra ) = func_get_args();
		$page = intval($page);
		  list($id, $alias ) = explode(':', $id);
		  if(($id) && (intval($id)!=$id))
		  if ($alias) {
		  list($alias, $added) = explode('#', $alias);
		  if($added) $added = '#'.$added;
		  $alias = str_replace(' ', '-', $alias);
		  $alias = str_replace('---', '-', $alias);
		  $alias = str_replace('--', '-', $alias);
		  }
		  $r = array('{id}' => $id, '{page}' => $page ? $page : 1, '{alias}' => $alias);
	} elseif ($type == 'all_script') {
		list(,,, $param, $extra ) = func_get_args();
		$param = str_replace('&amp;', '&', $param);
		$param = str_replace('?', '', $param);
		parse_str($param, $params);
		$script = $params['option'];
		if (!$script)
			$script = 'portal';
		else {
			unset($params['option']);
		}
		if (strexists($extra, 'showWindow') || strexists($extra, 'ajax') || strexists($param, '/') || strexists($param, '%2F') || strexists($param, '-')) {
			return '<a href="index.php?' . $param . '"' . dstripslashes($extra) . '>';
		}
		if (($apos = strrpos($param, '#')) !== FALSE) {
			$fextra = substr($param, $apos);
			$param = substr($param, 0, $apos);
		}
		$param = '';
		foreach ($params as $k => $v) {
			$param .= $k . '/' . rawurlencode($v) . '/';
		}
		if ($param)
			$param = substr($param, 0, - 1);
		if (!$param)
			$param = 'index';
		$r = array('{script}' => $script, '{param}' => substr($param, - 1) != '/' ? $param : substr($param, 0, strlen($param) - 1));
	} elseif ($type == 'site_default') {
		list(,,, $url ) = func_get_args();
		if (!preg_match('/^\w+\.php/i', $url)) {
			$host = '';
		}
		if (!$returntype) {
			return '<a href="' . $host . $url . '"';
		} else {
			return $host . $url;
		}
	}
	//解决链接中带有#的定位符引起的链接问题
	$appended = '';
	foreach((array)$r as $k=>$v){
		if(strpos($v, '#')){
			$vv = explode('#', $v);
			$r[$k] = $vv[0];
			unset($vv[0]);
			$appended .= '#'.implode('#', $vv);
		}
	}
	if (!isset($r['{alias}']) || !$r['{alias}']) {
		$_G['setting']['rewriterule'][$type] = str_replace(':{alias}', '', $_G['setting']['rewriterule'][$type]);
	}
	$href = str_replace(array_keys($r), $r, $_G['setting']['rewriterule'][$type]) . $appended . $fextra;
	$href = str_replace(':/', '/', $href);
	if (isset($added))
		$href.=$added;
	if (!$returntype) {
		return '<a href="' . $host . $href . '"' . dstripslashes($extra) . '>';
	} else {
		return $host . $href;
	}
}

function output() {
	global $_G, $db;
	if (defined('JYCMS_OUTPUTED')) {
		return;
	} else {
		define('JYCMS_OUTPUTED', 1);
	}
	$port = empty($_SERVER['SERVER_PORT']) || $_SERVER['SERVER_PORT'] == '80' ? '' : ':' . $_SERVER['SERVER_PORT'];
	$content = ob_get_contents();
	$content = compressjscss($content);
	if ($_G['setting']['rewritestatus']) {
		if ($_G['setting']['rewritestatus'] && !defined('IN_MODCP') && !defined('IN_ADMINCP')) {
			$s = str_replace('/', '/', $_G['siteurl']);
			$content = preg_replace('/href="([a-z]+)\.php/e', 'readdhost("\\1")', $content);
			$searcharray = $replacearray = array();
			$array = rewritedata();
			$content = preg_replace($array['search'], $array['replace'], $content);
		}
	}
	ob_end_clean();
	$_G['gzipcompress'] ? ob_start('ob_gzhandler') : ob_start();
	$content = preg_replace('@second\(s\)[\,\s0-9\t]+queries@is', 'second(s), ' . $db->querynum . ' quries', $content);
	echo $content;
	if ($_G['setting']['ftp']['connid']) {
		@ftp_close($_G['setting']['ftp']['connid']);
	}
	$_G['setting']['ftp'] = array();
	if (!empty($_G['blockupdate'])) {
		block_updatecache($_G['blockupdate']['bid']);
	}
	if (!empty($_G['tpl_block'])) {

	}
	/*
	  if (defined('CMS_DEBUG') && CMS_DEBUG) {
	  if ($db->sqldebug) {
	  require_once libfile('class/error');
	  $i = 1;
	  $taketime = 0;
	  foreach ($db->sqldebug as $sql) {
	  echo '<hr>' . cmsError::sqlhighlight($sql[0]) . '<br>';
	  echo '<b>Take time</b>:' . $sql[1] . '<br>';
	  $taketime += $sql[1];
	  echo '<b>Code tracing</b>:' . $sql[2];
	  }
	  if ($taketime) {
	  echo '<hr><b>Total time</b>:' . $taketime;
	  }
	  }
	  }
	 */
	maketplblockvalue();
}

function readdhost($s) {
	global $_G;
	return 'href="' . $_G['siteurl'] . $s . '.php';
}

function output_ajax() {
	$s = ob_get_contents();
	ob_end_clean();
	$s = preg_replace("/([\\x01-\\x08\\x0b-\\x0c\\x0e-\\x1f])+/", ' ', $s);
	$s = str_replace(array(chr(0), ']]>'), array(' ', ']]&gt;'), $s);
	return $s;
}

//更新积分
function updatecreditbyaction($action, $uid = 0, $extrasql = array(), $needle = '', $coef = 1, $update = 1, $fid = 0) {
	//exit($action);
	include_once libfile('class/credit');
	$credit = & credit::instance();
	if ($extrasql) {
		$credit->extrasql = $extrasql;
	}
	return $credit->execrule($action, $uid, $needle, $coef, $update, $fid);
}

function debuginfo() {
	global $_G, $db;
	if (getglobal('setting/debug')) {
		if (empty($db))
			$db = & DB::object();
		$_G['debuginfo'] = array('time' => number_format((dmicrotime() - $_G['starttime']), 6), 'queries' => $db->querynum, 'memory' => ucwords($_G['memory']));
		$_G['debuginfo']['sql'] = $db->sqldebug;
		return TRUE;
	} else {
		return FALSE;
	}
}

function adshow($parameter) {
	global $_G;
	if ($_G['inajax']) {
		return;
	}
	$adcontent = '';
	$params = explode('/', $parameter);
	$customid = 0;
	$customc = explode('_', $params[0]);
	if ($customc[0] == 'custom') {
		$params[0] = $customc[0];
		$customid = $customc[1];
	}
	loadcache('advs');
	$adids = array();
	$evalcode = &$_G['cache']['advs']['evalcode'][$params[0]];
	$parameters = &$_G['cache']['advs']['parameters'][$params[0]];
	$codes = &$_G['cache']['advs']['code'][$_G['basescript']][$params[0]];
	if (!empty($codes)) {
		foreach ($codes as $adid => $code) {
			$parameter = &$parameters[$adid];
			$checked = true;
			@eval($evalcode['check']);
			if ($checked) {
				$adids[] = $adid;
			}
		}
		if (!empty($adids)) {
			$adcode = $extra = '';
			if ($evalcode['create']) {
				@eval($evalcode['create']);
			} else {
				$count = count($adids);
				$adid = rand(0, $count - 1);
				$adcode = $codes[$adids[$adid]];
			}
			if (empty($notag)) {
				$adcontent = '<div' . ($params[1] != '' ? ' class="' . $params[1] . '"' : '') . $extra . '>' . $adcode . '</div>';
			} else {
				$adcontent = $adcode;
			}
		}
	}

	$adfunc = 'ad_' . $params[0];
	$hscript = $_G['basescript'] . (($do = !empty($_G['gp_do']) ? $_G['gp_do'] : (!empty($_GET['do']) ? $_GET['do'] : '')) ? '_' . $do : '');
	return $adcontent;
}

function showmessage($message, $url_forward = '', $values = array(), $extraparam = array(), $custom = 0) {
	global $_G;
	$param = array('header' => false, 'timeout' => null, 'refreshtime' => null, 'closetime' => null, 'locationtime' => null, 'alert' => null, 'return' => false, 'redirectmsg' => 0, 'msgtype' => 1, 'showmsg' => true, 'showdialog' => false, 'login' => false, 'handle' => false, 'extrajs' => '');
	$navtitle = lang('core', 'Information');
	if ($custom) {
		$alerttype = 'alert_info';
		$show_message = $message;
		include template('common/showmessage');
		dexit();
	}
	define('CACHE_FORBIDDEN', TRUE);
	$_G['setting']['msgforward'] = @intval($_G['setting']['msgforward']);
	$handlekey = $leftmsg = '';
	if (empty($_G['inajax']) && !empty($_G['gp_quickforward'])) {
		$param['header'] = true;
	}
	if (!empty($_G['inajax'])) {
		$handlekey = $_G['gp_handlekey'] = !empty($_G['gp_handlekey']) ? htmlspecialchars($_G['gp_handlekey']) : '';
		$param['handle'] = true;
	}
	if (!empty($_G['inajax'])) {
		$param['msgtype'] = empty($_G['gp_ajaxmenu']) && (empty($_POST) || !empty($_G['gp_nopost'])) ? 2 : 3;
	}
	if ($url_forward) {
		$param['timeout'] = true;
		if ($param['handle'] && !empty($_G['inajax'])) {
			$param['showmsg'] = false;
		}
	}
	foreach ($extraparam as $k => $v) {
		$param[$k] = $v;
	}
	if (array_key_exists('set', $extraparam)) {
		$setdata = array('1' => array('msgtype' => 3));
		if ($setdata[$extraparam['set']]) {
			foreach ($setdata[$extraparam['set']] as $k => $v) {
				$param[$k] = $v;
			}
		}
	}
	$timedefault = intval($param['refreshtime'] === null ? $_G['setting']['msgforward'] : $param['refreshtime']);
	if ($param['timeout'] !== null) {
		$refreshsecond = !empty($timedefault) ? $timedefault : 3;
		$refreshtime = $refreshsecond * 1000;
	} else {
		$refreshtime = $refreshsecond = 0;
	}
	if ($param['login'] && $_G['uid'] || $url_forward) {
		$param['login'] = false;
	}
	$param['header'] = $url_forward && $param['header'] ? true : false;
	if ($param['header']) {
		header("HTTP/1.1 301 Moved Permanently");
		dheader("location: " . str_replace('&amp;', '&', $url_forward));
	}
	$show_message = lang('message', $message, $values);
	if ($param['msgtype'] == 2 && $param['login']) {
		dheader('location: index.php?option=member&task=login&handlekey=' . $handlekey . '&infloat=yes&inajax=yes&guestmessage=yes');
	}
	$show_jsmessage = str_replace("'", "\\\'", strip_tags($show_message));
	if (!$param['showmsg']) {
		$show_message = '';
	}
	if ($param['msgtype'] == 3) {
		$show_message = str_replace(lang('message', 'return_search'), lang('message', 'return_replace'), $show_message);
	}
	$allowreturn = !$param['timeout'] && stristr($show_message, lang('message', 'return')) || $param['return'] ? true : false;
	if ($param['alert'] === null) {
		$alerttype = $url_forward ? (preg_match('/\_(succeed|success)$/', $message) ? 'alert_right' : 'alert_info') : ($allowreturn ? 'alert_error' : 'alert_info');
	} else {
		$alerttype = 'alert_' . $param['alert'];
	}
	$extra = '';
	if ($param['handle']) {
		$valuesjs = $comma = $subjs = '';
		foreach ($values as $k => $v) {
			if (is_array($v)) {
				$subcomma = '';
				foreach ($v as $subk => $subv) {
					$subjs .= $subcomma . '\'' . $subk . '\':\'' . $subv . '\'';
					$subcomma = ',';
				}
				$valuesjs .= $comma . '\'' . $k . '\':{' . $subjs . '}';
			} else {
				$valuesjs .= $comma . '\'' . $k . '\':\'' . $v . '\'';
			}
			$comma = ',';
		}
		$valuesjs = '{' . $valuesjs . '}';
		if ($url_forward) {
			$extra .= 'if($$$(\'return_' . $handlekey . '\')) $$$(\'return_' . $handlekey . '\').className=\'onerror\';if(typeof succeedhandle_' . $handlekey . '==\'function\') {succeedhandle_' . $handlekey . '(\'' . $url_forward . '\', \'' . $show_jsmessage . '\', ' . $valuesjs . ');}';
		} else {
			$extra .= 'if(typeof errorhandle_' . $handlekey . '==\'function\') {errorhandle_' . $handlekey . '(\'' . $show_jsmessage . '\', ' . $valuesjs . ');}';
		}
	}
	if ($param['closetime'] !== null) {
		$param['closetime'] = $param['closetime'] === true ? $timedefault : $param['closetime'];
		$leftmsg = $param['closetime'] . lang('message', 'seconds to close this window');
	}
	if ($param['locationtime'] !== null) {
		$param['locationtime'] = $param['locationtime'] === true ? $timedefault : $param['locationtime'];
		$leftmsg = $param['locationtime'] . lang('message', 'seconds to jump next page');
	}
	if ($handlekey) {
		if ($param['showdialog']) {
			$st = $param['closetime'] !== null ? 'setTimeout("hideMenu(\'fwin_dialog\', \'dialog\')", ' . ($param['closetime'] * 1000) . ');' : '';
			$st .= $param['locationtime'] !== null ? 'setTimeout("window.location.href =\'' . $url_forward . '\';", ' . ($param['locationtime'] * 1000) . ');' : '';
			$extra .= 'hideWindow(\'' . $handlekey . '\');showDialog(\'' . $show_jsmessage . '\', \'notice\', null, ' . ($param['locationtime'] !== null ? 'function () { window.location.href =\'' . $url_forward . '\'; }' : 'null') . ', 0, null, \'' . $leftmsg . '\');' . $st;
			$param['closetime'] = null;
			$st = '';
		}
		if ($param['closetime'] !== null) {
			$extra .= 'setTimeout("hideWindow(\'' . $handlekey . '\')", ' . ($param['closetime'] * 1000) . ');';
		}
	} else {
		$st = $param['locationtime'] !== null ? 'setTimeout("window.location.href =\'' . $url_forward . '\';", ' . ($param['locationtime'] * 1000) . ');' : '';
	}
	if (!$extra && $param['timeout']) {
		$extra .= 'setTimeout("window.location.href =\'' . $url_forward . '\';", ' . $refreshtime . ');';
	}
	$show_message .= $extra ? '<script type="text/javascript" reload="1">' . $extra . $st . '</script>' : '';
	$show_message .= $param['extrajs'] ? $param['extrajs'] : '';
	include template('common/showmessage');
	dexit();
}

function submitcheck($var = 'submit', $allowget = 0) {
	if (!getgpc($var)) {
		return FALSE;
	} else {
		global $_G;
		if ($allowget || ($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_G['gp_formhash']) && $_G['gp_formhash'] == formhash() && empty($_SERVER['HTTP_X_FLASH_VERSION']) && (empty($_SERVER['HTTP_REFERER']) || preg_replace("/https?:\/\/([^\:\/]+).*/i", "\\1", $_SERVER['HTTP_REFERER']) == preg_replace("/([^\:]+).*/", "\\1", $_SERVER['HTTP_HOST'])))) {
			return TRUE;
		} else {
			showmessage('Your request origin is not correct, can not be submitted.');
		}
	}
}

function multi($num, $perpage, $curpage, $mpurl, $maxpages = 0, $page = 10, $autogoto = FALSE, $simple = FALSE) {
	global $_G;
	$ajaxtarget = !empty($_G['gp_ajaxtarget']) ? " ajaxtarget=\"" . htmlspecialchars($_G['gp_ajaxtarget']) . "\" " : '';
	$a_name = '';
	if (strpos($mpurl, '#') !== FALSE) {
		$a_strs = explode('#', $mpurl);
		$mpurl = $a_strs[0];
		$a_name = '#' . $a_strs[1];
	}
	if (defined('IN_ADMINCP')) {
		$shownum = $showkbd = TRUE;
		$prev = '&lsaquo;&lsaquo;';
		$next = '&rsaquo;&rsaquo;';
	} else {
		$shownum = $showkbd = FALSE;
		$prev = lang('core', 'Prev page');
		$next = lang('core', 'Next page');
	}
	$multipage = '';
	$mpurl .= strpos($mpurl, '?') !== FALSE ? '&amp;' : '?';
	$realpages = 1;
	$_G['page_next'] = 0;
	if ($num > $perpage) {
		$offset = floor($page * 0.5);
		$realpages = @ceil($num / $perpage);
		$pages = $maxpages && $maxpages < $realpages ? $maxpages : $realpages;
		if ($page > $pages) {
			$from = 1;
			$to = $pages;
		} else {
			$from = $curpage - $offset;
			$to = $from + $page - 1;
			if ($from < 1) {
				$to = $curpage + 1 - $from;
				$from = 1;
				if ($to - $from < $page) {
					$to = $page;
				}
			} elseif ($to > $pages) {
				$from = $pages - $page + 1;
				$to = $pages;
			}
		}
		$_G['page_next'] = $to;
		$multipage = ($curpage - $offset > 1 && $pages > $page ? '<a href="' . $mpurl . 'page=1' . $a_name . '" class="first"' . $ajaxtarget . '>1 ...</a>' : '') . ($curpage > 1 && !$simple ? '<a href="' . $mpurl . 'page=' . ($curpage - 1) . $a_name . '" ' . $ajaxtarget . '>' . $prev . '</a>' : '<span>' . $prev . '</span>');
		for ($i = $from; $i <= $to; $i++) {
			$multipage .= $i == $curpage ? '<strong>' . $i . '</strong>' : '<a href="' . $mpurl . 'page=' . $i . ($ajaxtarget && $i == $pages && $autogoto ? '#' : $a_name) . '"' . $ajaxtarget . '>' . $i . '</a>';
		}
		$multipage .= ( $to < $pages ? '<a href="' . $mpurl . 'page=' . $pages . $a_name . '" class="last"' . $ajaxtarget . '>... ' . $realpages . '</a>' : '') . ($curpage < $pages && !$simple ? '<a href="' . $mpurl . 'page=' . ($curpage + 1) . $a_name . '" ' . $ajaxtarget . '>' . $next . '</a>' : '<span>' . $next . '</span>') . ($showkbd && !$simple && $pages > $page && !$ajaxtarget ? '<kbd><input type="text" name="custompage" size="3" onkeydown="if(event.keyCode==13) {window.location=\'' . $mpurl . 'page=\'+this.value; doane(event);}" /></kbd>' : '');
		$multipage = $multipage ? '<div class="pg">' . ($shownum && !$simple ? '<em>&nbsp;' . $num . '&nbsp;</em>' : '') . $multipage . '</div>' : '';
	}
	$maxpage = $realpages;
	return $multipage;
}

function censor($message, $modword = NULL, $return = FALSE) {
	require_once libfile('class/censor');
	$censor = cmsCensor::instance();
	$censor->check($message, $modword);
	if ($censor->modbanned()) {
		$wordbanned = implode(', ', $censor->words_found);
		if ($return) {
			return array('message' => lang('message', 'word_banned', array('wordbanned' => $wordbanned)));
		}
		showmessage('word_banned', '', array('wordbanned' => $wordbanned));
	}
	return $message;
}

function censormod($message) {
	global $_G;
	if ($_G['group']['ignorecensor']) {
		return false;
	}
	require_once libfile('class/censor');
	$censor = cmsCensor::instance();
	$censor->check($message);
	return $censor->modmoderated();
}

function runlog($file, $message, $halt = 0) {
	global $_G;
	$nowurl = $_SERVER['REQUEST_URI'] ? $_SERVER['REQUEST_URI'] : ($_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME']);
	$log = dgmdate($_G['timestamp'], 'Y-m-d H:i:s') . "\t" . $_G['clientip'] . "\t$_G[uid]\t{$nowurl}\t" . str_replace(array("\r", "\n"), array(' ', ' '), trim($message)) . "\n";
	$yearmonth = dgmdate($_G['timestamp'], 'Ym');
	$logdir = ROOT_PATH . './data/log/';
	if (!is_dir($logdir))
		dmkdir($logdir, 0777);
	$logfile = $logdir . $yearmonth . '_' . $file . '.php';
	if (@filesize($logfile) > 2048000) {
		$dir = opendir($logdir);
		$length = strlen($file);
		$maxid = $id = 0;
		while ($entry = readdir($dir)) {
			if (strexists($entry, $yearmonth . '_' . $file)) {
				$id = intval(substr($entry, $length + 8, - 4));
				$id > $maxid && $maxid = $id;
			}
		}
		closedir($dir);
		$logfilebak = $logdir . $yearmonth . '_' . $file . '_' . ($maxid + 1) . '.php';
		@rename($logfile, $logfilebak);
	}
	$buffer = "<?PHP exit;?>\t" . str_replace(array('<?', '?>', "\r", "\n"), '', $log) . "\n";
	cmsFS::write($logfile, $buffer, 'a');
	if ($halt)
		exit();
}

function stripsearchkey($string) {
	$string = trim($string);
	$string = str_replace('*', '%', addcslashes($string, '%_'));
	$string = str_replace('_', '\_', $string);
	return $string;
}

function dmkdir($dir, $mode = 0777, $makeindex = TRUE) {
	if (!is_dir($dir)) {
		dmkdir(dirname($dir));
		@mkdir($dir, $mode);
		if (!empty($makeindex)) {
			@touch($dir . '/index.html');
			@chmod($dir . '/index.html', 0777);
		}
	}
	return true;
}

function dreferer($default = '') {
	global $_G;
	$default = empty($default) ? $GLOBALS['_t_curapp'] : '';
	if (empty($_G['referer'])) {
		$referer = !empty($_G['gp_referer']) ? $_G['gp_referer'] : $_SERVER['HTTP_REFERER'];
		$_G['referer'] = preg_replace("/([\?&])((sid\=[a-z0-9]{6})(&|$))/i", '\\1', $referer);
		$_G['referer'] = substr($_G['referer'], - 1) == '?' ? substr($_G['referer'], 0, - 1) : $_G['referer'];
	} else {
		$_G['referer'] = htmlspecialchars($_G['referer']);
	}
	if (strpos($_G['referer'], 'index.php?option=member&task=logging')) {
		$_G['referer'] = $default;
	}
	return strip_tags($_G['referer']);
}

function ftpcmd($cmd, $arg1 = '') {
	static $ftp;
	$ftpon = getglobal('setting/ftp/on');
	if (!$ftpon) {
		return $cmd == 'error' ? - 101 : 0;
	} elseif ($ftp == null) {
		require_once libfile('class/ftp');
		$ftp = & cmsFTP::instance();
	}
	if (!$ftp->enabled) {
		return 0;
	} elseif ($ftp->enabled && !$ftp->connectid) {
		$ftp->connect();
	}
	switch ($cmd) {
		case 'upload' :
			return $ftp->upload(getglobal('setting/attachdir') . '/' . $arg1, $arg1);
			break;
		case 'delete' :
			return $ftp->ftp_delete($arg1);
			break;
		case 'close' :
			return $ftp->ftp_close();
			break;
		case 'error' :
			return $ftp->error();
			break;
		case 'object' :
			return $ftp;
			break;
		default :
			return false;
	}
}

/**
 * 编码转换
 *
 * @global array $_G
 * @param string $str 要转换的字符串
 * @param string $in_charset 原编码
 * @param string $out_charset 目标编码
 * @param boolean $ForceTable 强制使用编码表
 * @return string
 */
function diconv($str, $in_charset, $out_charset = CHARSET, $ForceTable = FALSE) {
	global $_G;
	$in_charset = strtoupper($in_charset);
	$out_charset = strtoupper($out_charset);
	if ($in_charset != $out_charset) {
		require_once libfile('class/chinese');
		$chinese = new Chinese($in_charset, $out_charset, $ForceTable);
		$strnew = $chinese->Convert($str);
		if (!$ForceTable && !$strnew && $str) {
			$chinese = new Chinese($in_charset, $out_charset, 1);
			$strnew = $chinese->Convert($str);
		}
		return $strnew;
	} else {
		return $str;
	}
}

function writelog($file, $log) {
	global $_G;
	$yearmonth = dgmdate(TIMESTAMP, 'Ym', $_G['setting']['timeoffset']);
	$logdir = ROOT_PATH . './data/log/';
	$logfile = $logdir . $yearmonth . '_' . $file . '.php';
	if (@filesize($logfile) > 2048000) {
		$dir = opendir($logdir);
		$length = strlen($file);
		$maxid = $id = 0;
		while ($entry = readdir($dir)) {
			if (strexists($entry, $yearmonth . '_' . $file)) {
				$id = intval(substr($entry, $length + 8, - 4));
				$id > $maxid && $maxid = $id;
			}
		}
		closedir($dir);
		$logfilebak = $logdir . $yearmonth . '_' . $file . '_' . ($maxid + 1) . '.php';
		@rename($logfile, $logfilebak);
	}
	if ($fp = @fopen($logfile, 'a')) {
		@flock($fp, 2);
		$log = is_array($log) ? $log : array($log);
		foreach ($log as $tmp) {
			fwrite($fp, "<?PHP exit;?>\t" . str_replace(array('<?', '?>'), '', $tmp) . "\n");
		}
		fclose($fp);
	}
}

/**
 * 添加通知
 *
 * @global array $_G
 * @param int $touid 用户ID
 * @param string $type 通知类型
 * @param string $note 通知内容
 * @param string $notevars 内容中涉及到的变量的值
 * @param boolean $system 是否系统通知
 * @return <type>
 */
function notification_add($touid, $type, $note, $notevars = array(), $system = 0) {
	global $_G;
	$tospace = array('uid' => $touid);
	if ($_G['uid']) {
		$notevars['actor'] = "<a href=\"index.php?option=member&task=profile&uid=$_G[uid]\">" . $_G['member']['username'] . "</a>";
	} else {
		require_once libfile('function/misc');
		$notevars['actor'] = convertip($_G['clientip']) . '网友 ';
	}
	if (!is_numeric($type)) {
		$notestring = lang('notification', $note, $notevars);
	} else {
		$notestring = $note;
	}
	$oldnote = array();
	if ($notevars['from_id'] && $notevars['from_idtype']) {
		$oldnote = DB::fetch_first("SELECT * FROM #__common_notification
			WHERE uid='$touid' AND from_id='$notevars[from_id]' AND from_idtype='$notevars[from_idtype]'");
	}
	if (empty($oldnote['from_num']))
		$oldnote['from_num'] = 0;
	$setarr = array('uid' => $touid, 'type' => $type, 'new' => 1, 'authorid' => $_G['uid'], 'author' => $_G['username'], 'note' => addslashes($notestring), 'dateline' => $_G['timestamp'], 'from_id' => $notevars['from_id'], 'from_idtype' => $notevars['from_idtype'], 'from_num' => ($oldnote['from_num'] + 1));
	if ($system) {
		$setarr['authorid'] = 0;
		$setarr['author'] = '';
	}
	if ($oldnote['id']) {
		DB::update('common_notification', $setarr, array('id' => $oldnote['id']));
	} else {
		$oldnote['new'] = 0;
		DB::insert('common_notification', $setarr);
	}
	if (empty($oldnote['new'])) {
		DB::query("UPDATE #__common_member SET notifications=notifications+1, newprompt=newprompt+1 WHERE uid='$touid'");
	}
}

function updatediytemplate($targettplname = '') {
	global $_G;
	$r = false;
	$where = empty($targettplname) ? '' : " WHERE targettplname='$targettplname'";
	$query = DB::query("SELECT * FROM #__common_diy_data$where");
	require_once libfile('function/diy');
	while ($value = DB::fetch($query)) {
		$r = save_diy_data($value['primaltplname'], $value['targettplname'], unserialize($value['diycontent']));
	}
	return $r;
}

function ipaccess($ip, $accesslist) {
	return preg_match("/^(" . str_replace(array("\r\n", ' '), array('|', ''), preg_quote($accesslist, '/')) . ")/", $ip);
}

function ipbanned($onlineip) {
	global $_G;
	if ($_G['setting']['ipaccess'] && !ipaccess($onlineip, $_G['setting']['ipaccess'])) {
		return TRUE;
	}
	loadcache('ipbanned');
	if (empty($_G['cache']['ipbanned'])) {
		return FALSE;
	} else {
		if ($_G['cache']['ipbanned']['expiration'] < TIMESTAMP) {
			require_once libfile('function/cache');
			updatecache('ipbanned');
		}
		return preg_match("/^(" . $_G['cache']['ipbanned']['regexp'] . ")$/", $onlineip);
	}
}

function bannedmsg($message) {
	$message = lang('message', $message);
	$title = lang('error', 'System Message');
	$charset = CHARSET;
	include_once template("common/bannedmsg");
	die();
}

if (!function_exists('file_put_contents')) {
	if (!defined('FILE_APPEND'))
		define('FILE_APPEND', 8);

	function file_put_contents($filename, $data, $flag = 0) {
		$return = false;
		if ($fp = @fopen($filename, $flag != FILE_APPEND ? 'w' : 'a')) {
			if ($flag == LOCK_EX)
				@flock($fp, LOCK_EX);
			$return = fwrite($fp, is_array($data) ? implode('', $data) : $data);
			fclose($fp);
		}
		return $return;
	}

}

function checkperm($perm) {
	global $_G;
	return (empty($_G['group'][$perm]) ? '' : $_G['group'][$perm]);
}

function return_bytes($val) {
	$val = trim($val);
	$last = strtolower($val{strlen($val) - 1});
	switch ($last) {
		case 'g' :
			$val *= 1024;
		case 'm' :
			$val *= 1024;
		case 'k' :
			$val *= 1024;
	}
	return $val;
}

/**
 * 生成系统回调函数
 *
 * @param unknown_type $ignorefile
 * @param unknown_type $line
 * @return unknown
 */
function debugmessage($ignorefile = '', $line = 0) {
	$result = '<br />';
	if (function_exists('debug_backtrace')) {
		$i = 1;
		foreach (debug_backtrace() as $back) {
			if (@$back['file']) {
				if (!$ignorefile) {
					$result .= "&nbsp;&nbsp;&nbsp;&nbsp;" . $i . ':' . str_replace(ROOT_PATH, '', $back['file']) . ':' . $back['line'] . '<br>';
					$i++;
				} else {
					if (basename($back['file']) != $ignorefile && $back['line'] != $line) {
						$result .= "&nbsp;&nbsp;&nbsp;&nbsp;" . $i . ':' . str_replace(ROOT_PATH, '', $back['file']) . ':' . $back['line'] . '<br>';
						$i++;
					}
				}
			}
		}
	}
	return $result;
}

/**
 * 格式化输出信息
 *
 * @param 字符串/数组 $array 要输出的信息
 * @param 逻辑值 $exit 是否需要退出
 */
function pre($array, $toexit = false) {
	if ($array) {
		if (is_string($array)) {
			echo '<br>';
			echo $array;
			echo '<br>';
		} else {
			echo "<div style='text-align:left;color:#000;background-color:#fff;'><pre>";
			print_r($array);
			echo "</pre></div>";
		}
		echo debugmessage(basename(__FILE__), __LINE__);
	}
	if ($toexit)
		exit();
}

function isopera() {
	$useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
	if (strpos($useragent, 'opera') !== false) {
		preg_match('/opera(\/| )([0-9\.]+)/', $useragent, $regs);
		return $regs[2];
	}
	return FALSE;
}

function dreaddir($dir, $extarr = array()) {
	$dirs = array();
	if ($dh = opendir($dir)) {
		while (($file = readdir($dh)) !== false) {
			if (!empty($extarr) && is_array($extarr)) {
				if (in_array(strtolower(fileext($file)), $extarr)) {
					$dirs[] = $file;
				}
			} else if ($file != '.' && $file != '..') {
				$dirs[] = $file;
			}
		}
		closedir($dh);
	}
	return $dirs;
}

function obclean() {
	ob_end_clean();
	if (getglobal('config/output/gzip') && function_exists('ob_gzhandler')) {
		ob_start('ob_gzhandler');
	} else {
		ob_start();
	}
}

function getstr($string, $length, $in_slashes = 0, $out_slashes = 0, $bbcode = 0, $html = 0) {
	global $_G;
	$string = trim($string);
	if ($in_slashes) {
		$string = dstripslashes($string);
	}
	if ($html < 0) {
		$string = preg_replace("/(\<[^\<]*\>|\r|\n|\s|\[.+?\])/is", ' ', $string);
	} elseif ($html == 0) {
		$string = dhtmlspecialchars($string);
	}
	if ($length) {
		$string = cutstr($string, $length);
	}
	if ($bbcode) {
		require_once ROOT_PATH . './source/class/class_bbcode.php';
		$bb = & bbcode::instance();
		$string = $bb->bbcode2html($string, $bbcode);
	}
	if ($out_slashes) {
		$string = daddslashes($string);
	}
	return trim($string);
}

function pic_delete($pic, $type, $thumb, $remote) {
	global $_G;
	if ($remote) {
		ftpcmd('delete', $type . '/' . $pic);
		if ($thumb) {
			ftpcmd('delete', $type . '/' . $pic . '.thumb.jpg');
		}
		ftpcmd('close');
	} else {
		@unlink($_G['setting']['attachdir'] . '/' . $type . '/' . $pic);
		if ($thumb) {
			@unlink($_G['setting']['attachdir'] . '/' . $type . '/' . $pic . '.thumb.jpg');
		}
	}
}

/**
 * 上传图片
 *
 * @param array $FILES 文件数组
 * @param string $type 上传的图片类型
 * @param int $thumb_width
 * @param int $thumb_height
 * @param <type> $thumb_type
 * @return int
 */
function pic_upload($FILES, $type = 'album', $thumb_width = 0, $thumb_height = 0, $thumb_type = 2) {
	require_once libfile('class/upload');
	$upload = new cmsUpload ();
	$result = array('pic' => '', 'thumb' => 0, 'remote' => 0);
	$upload->init($FILES, $type);
	if ($upload->error()) {
		return array();
	}
	$upload->save();
	if ($upload->error()) {
		return array();
	}
	$result['pic'] = $upload->attach['attachment'];
	if ($thumb_width && $thumb_height) {
		require_once libfile('class/image');
		$image = new image ();
		if ($image->Thumb($upload->attach['target'], '', $thumb_width, $thumb_height, $thumb_type)) {
			$result['thumb'] = 1;
		}
	}
	if (getglobal('setting/ftp/on')) {
		if (ftpcmd('upload', $type . '/' . $upload->attach['attachment'])) {
			if ($result['thumb']) {
				ftpcmd('upload', $type . '/' . $upload->attach['attachment'] . '.thumb.jpg');
			}
			ftpcmd('close');
			$result['remote'] = 1;
		} else {
			if (getglobal('setting/ftp/mirror')) {
				@unlink($upload->attach['target']);
				@unlink($upload->attach['target'] . '.thumb.jpg');
				return array();
			}
		}
	}
	return $result;
}

/**
 * 调试输出信息
 *
 * @param string $str 要输出的信息
 * @param int $h 编辑框高度
 * @return string 输出信息
 */
function code($str, $h = 300) {
	$h = intval($h);
	if (!$h)
		$h = 300;
	return '<textarea style="width: 98%; height: ' . $h . 'px;">' . $str . '</textarea>';
}

/**
 * 获得当前的域名
 *
 * @return  string
 */
function get_domain() {
	/* 协议 */
	$protocol = (isset($_SERVER['HTTPS']) && (strtolower($_SERVER['HTTPS']) != 'off')) ? 'https://' : 'http://';
	/* 域名或IP地址 */
	if (isset($_SERVER['HTTP_X_FORWARDED_HOST'])) {
		$host = $_SERVER['HTTP_X_FORWARDED_HOST'];
	} elseif (isset($_SERVER['HTTP_HOST'])) {
		$host = $_SERVER['HTTP_HOST'];
	} else {
		/* 端口 */
		if (isset($_SERVER['SERVER_PORT'])) {
			$port = ':' . $_SERVER['SERVER_PORT'];
			if ((':80' == $port && 'http://' == $protocol) || (':443' == $port && 'https://' == $protocol)) {
				$port = '';
			}
		} else {
			$port = '';
		}
		if (isset($_SERVER['SERVER_NAME'])) {
			$host = $_SERVER['SERVER_NAME'] . $port;
		} elseif (isset($_SERVER['SERVER_ADDR'])) {
			$host = $_SERVER['SERVER_ADDR'] . $port;
		}
	}
	return $protocol . $host;
}

/**
 * 获取当前的子域名
 * @global array $_G
 * @global core $mainframe
 * @return string 子域名
 */
function get_subdomain() {
	global $_G, $mainframe;
	$curr_url_info = parse_url(get_domain());
	$curr_domain = strtolower($curr_url_info['host']);
	$main_url_info = parse_url($_G['siteurl']);
	$main_doamin = strtolower($main_url_info['host']);
	if ($curr_domain == $main_domain) {/* 当前域名不是二级域名 */
		return false;
	}
	$tmp = explode('.', $curr_domain);
	return $tmp[0];
}

/**
 * 获取子域名对应的分类ID
 *
 * @param string $subdomain 子域名
 * @return int 对应的分类ID
 */
function get_subdomain_cate_id($subdomain) {
	$sql = "SELECT * FROM #__common_category WHERE foldername='$subdomain'";
	$qeury = DB::query($sql);
	$row = DB::fetch_array($qeury);
	if ($row)
		return $row['catid'];
	return false;
}

/**
 * 压缩
 *
 * @param string $str 要压缩的字符串
 * @return string 压缩后的字符串
 */
function compress($str) {
	if (is_array($str))
		$str = serialize($str);
	return base64_encode(gzdeflate($str, 9));
}

/**
 * 解压缩
 *
 * @param string $str 要解压的字符串
 * @return string 解压后的字符串
 * @see common.func.php|compress
 */
function decompress($str) {
	return gzinflate(base64_decode($str));
}

function compressjscss($body) {
	return $body;
	global $_G;
	$isGZ = $_G['gzipcompress'];
	$siteurl = $_G['siteurl'];
	$isok = true;
	require_once libfile('class/mergejscss');
	$compressor = new jsCssCompressor ();
	$scriptRegex = "/<script [^>]+(\/>|><\/script>)/i";
	$jsRegex = "/([^\"\'=]+\.(js))[\"\']/i";
	preg_match_all($scriptRegex, $body, $matches_js);
	$scripts = @implode('', $matches_js[0]);
	preg_match_all($jsRegex, $scripts, $matches);
	$scriptFiles = array();
	foreach ($matches[1] as $script) {
		//if(isInternal($script)){
		$parts = @explode($siteurl, $script);
		if (count($parts) > 1 && endwith($parts[1], '.js')) {
			$script = ROOT_PATH . '/' . $parts[1];
			$script = replaceSperator($script);
			$scriptFiles[] = $script;
		} else if (endwith($script, '.js')) {
			$script = ROOT_PATH . '/' . $script;
			$script = replaceSperator($script);
			if (file_exists($script)) {
				$scriptFiles[] = $script;
			} else {
				$script = ROOT_PATH . '/' . $script;
				$script = replaceSperator($script);
				if (file_exists($script)) {
					$scriptFiles[] = $script;
				}
			}
		}
		//}
	}
	$ExcludeJs = array('calendar.js', 'portal_upload.js', 'slimbox.js', '_diy.js'); //要忽略的JS文件
	//remove all ingnored files
	$scriptFiless = array();
	foreach ($scriptFiles as $k => $sf) {
		$shouldIgnore = false;
		if (isset($ExcludeJs) && count($ExcludeJs)) {
			foreach ($ExcludeJs as $exd) {
				if ($exd && endwith($sf, $exd)) {
					$shouldIgnore = true;
					break;
				}
			}
		}

		if (!$shouldIgnore) {
			$scriptFiless[] = $sf;
		}
	}
	$scriptFiles = array_unique($scriptFiless);
	if (!empty($scriptFiles)) {
		$singleJsFileName = md5($siteurl . @implode('', $scriptFiles)) . '.js';
		if ($isGZ) {
			$singleJsFileName .= '.gz';
		}
		$jsBaseDir = ROOT_PATH . '/data/cache/js';
		if (!file_exists($jsBaseDir)) {
			mkdir($jsBaseDir);
			file_put_contents($jsBaseDir . '/index.html', '');
		}
		$jsSingle = $jsBaseDir . '/' . $singleJsFileName;
		if ($isDebug || !file_exists($jsSingle)) {
			$isok = $compressor->makeJsOld($siteurl, ROOT_PATH, $scriptFiles, $jsSingle, $isGZ, $jqueryNoConflict, $jquery);
		}
		if ($isok) {
			replaceJs(NULL, $ExcludeJs);
			$body = preg_replace_callback($scriptRegex, "replaceJs", $body);
			$newImportJs = '<script type="text/javascript" src="' . $siteurl . 'source/CssJsCompress/js.php?js=' . $singleJsFileName . '"></script></head>';
			$body = preg_replace('/<\/head>/i', $newImportJs, $body, 1);
		}
	}
	//done js
	$excludeCss = array('style.css'); //要忽略的CSS文件
	$conditionRegex = "/<\!--\[if.*?\[endif\]-->/is";
	preg_match_all($conditionRegex, $body, $conditonMatches);
	$linksRegex = "|<link[^>]+[/]?>((.*)</[^>]+>)?|U";
	if (!empty($conditonMatches)) {
		preg_match_all($linksRegex, @implode('', $conditonMatches[0]), $conditionCss);
		if (!empty($conditionCss[0])) {
			$cssRegex = "/([^\"\'=]+\.(css))[\"\']/i";
			preg_match_all($cssRegex, @implode('', $conditionCss[0]), $conditionCssFiles);
			if (!empty($conditionCssFiles[1])) {
				foreach ($conditionCssFiles[1] as $conditionalCss) {
					$conditionalCss = fileName($conditionalCss);
				}
			}
		}
	}
	//end of conditional css and javascript files
	$cssRegex = "/([^\"\'=]+\.(css))[\"\']/i";
	preg_match_all($linksRegex, $body, $matches);
	$links = @implode('', $matches[0]);
	preg_match_all($cssRegex, $links, $matches);
	$cssLinks = array();
	foreach ($matches[1] as $link) {
		//if(isInternal($link)){
		$parts = @explode($siteurl, $link);
		if (count($parts) > 1 && strpos($parts[1], '.css')) {
			$link = ROOT_PATH . '/' . $parts[1];
			$link = replaceSperator($link);
			$cssLinks[] = $link;
		} else if (strpos($link, '.css')) {
			$link = ROOT_PATH . '/' . $link;
			$link = replaceSperator($link);
			if (file_exists($link)) {
				$cssLinks[] = $link;
			} else {
				$link = ROOT_PATH . '/' . $link;
				$link = replaceSperator($link);
				if (file_exists($link)) {
					$cssLinks[] = $link;
				}
			}
		}
		//}
	}
	$orderedCss = array();
	$cssLinks = array_unique($cssLinks);
	foreach ($cssLinks as $css) {
		$shouldIgnore = false;
		if (is_array($excludeCss))
			foreach ($excludeCss as $exd) {
				if ($exd && endwith($css, $exd)) {
					$shouldIgnore = true;
					break;
				}
			}
		if (!$shouldIgnore) {
			$orderedCss[] = $css;
		}
	}
	$cssLinks = $orderedCss;

	// print_r($cssLinks);
	if (!empty($cssLinks)) {
		$singlecssFileName = md5($siteurl . @implode('', $cssLinks)) . '.css';
		if ($isGZ) {
			$singlecssFileName .= '.gz';
		}
		$cssBaseDir = ROOT_PATH . '/data/cache/css';
		if (!file_exists($cssBaseDir)) {
			mkdir($cssBaseDir);
			file_put_contents($cssBaseDir . '/index.html', '');
		}
		$cssSingle = $cssBaseDir . '/' . $singlecssFileName;
		if ($isDebug || !file_exists($cssSingle)) {
			$isok = $compressor->makeCssOld($siteurl, ROOT_PATH, $cssLinks, $cssSingle, $isGZ);
		}
		if ($isok) {
			replaceCss(NULL, $excludeCss);
			$body = preg_replace_callback($linksRegex, 'replaceCss', $body);
			$newImportCss = '<link  rel="stylesheet" type="text/css" href="' . $siteurl . 'source/CssJsCompress/css.php?css=' . $singlecssFileName . '"/></head>';
			$body = preg_replace('/<head[^>]*>/i', $newImportCss, $body, 1);
		}
	}
	//done css
	require_once (ROOT_PATH . '/source/CssJsCompress/Minify/HTML.php');
	$body = Minify_HTML::minify($body);
	return $body;
}

/**
 * 生成页面中的标签缓存
 *
 */
function maketplblockvalue() {
	global $_G;
	if (!empty($_G['tpl_block'])) {
		//文本存储
		foreach ($_G['tpl_block'] as $cachekey => $tplvalue) {
			$cachedir = ROOT_PATH . 'data/cache/block/' . substr($cachekey, 0, 2);
			$dircheck = cmsFS::autocreatePath($cachedir);
			if ($dircheck) {
				$cachefile = $cachedir . '/' . $cachekey . '.cache.data';
				cmsFS::write($cachefile, $tplvalue['value']);
			}
		}
	}
}

function cuthtmltag($str, $tag) {
	$str = str_replace('< ', '<', $str);
	$str = str_replace('/>', '>', $str);
	$str = str_replace(' >', '>', $str);
	$begin = '<' . $tag;
	$end = '</' . $tag . '>';
	$i = 0;
	$endlen = strlen($end);
	while (stripos($str, $begin)) {
		$pos = stripos($str, $begin);
		$i1 = stripos($str, $end, $pos);
		//echo 'Find '.$tag.', From '. $pos.' to '.$i1.'<br>';
		if ($i1) {
			$str = substr_replace($str, '', $pos, $i1 + $endlen - $pos);
		} else {
			$str = substr($str, 0, $pos);
		}
		//$i++;
		//if($i>20) break;
	}
	return $str;
}

/**
 * 用于后台HTML的显示调用函数。
 *
 * @param 显示信息数组 $showarr:
 * return 转换后的HTML代码
 */
function label($showarr) {
	$thetext = $htmltext = '';
	$required = array(
		'value' => '',
		'getvalue' => false,
		'cellspacing' => 0,
		'note' => '',
		'first' => false,
		'required' => false,
		'opkey' => '',
		'opvalue' => '',
		'width' => 0,
		'valid' => '',
		'values' => array(),
		'height' => 60
	);
	foreach ($required as $k => $v) {
		if (!isset($showarr[$k]))
			$showarr[$k] = $v;
	}

	$showarr['value'] = preg_replace('/\{([a-z_]+)\}/iesU', 'processvalue("\\1", "' . $showarr['getvalue'] . '")', $showarr['value']);
	//$showarr['value'] = addcslashes($showarr['value'], '"');
	if (!isset($showarr['name']))
		$showarr['name'] = '';
	if (!isset($showarr['size']))
		$showarr['size'] = 30;
	if (!isset($showarr['maxlength']))
		$showarr['maxlength'] = '';
	if (!isset($showarr['value']))
		$showarr['value'] = '';
	if (!isset($showarr['options']))
		$showarr['options'] = array();
	if (!isset($showarr['other']))
		$showarr['other'] = '';
	if (!isset($showarr['display']))
		$showarr['display'] = '';
	if (!isset($showarr['title']))
		$showarr['title'] = '';
	if (!isset($showarr['fileurl']))
		$showarr['fileurl'] = substr($showarr['value'], 1);
	if (!isset($showarr['rows']))
		$showarr['rows'] = '5';
	if ($showarr['type'] == 'inputmode') {
		$showarr['type'] = 'select';
		$showarr['options'] = array(
			'' => '请选择',
			'input' => '直接输入',
			'textarea' => '多行文本框输入',
			'editor' => '可视化编辑器',
			'file' => '文件上传',
			'upload' => '批量文件上传',
			'uploadpic' => '图片上传',
			'yesorno' => '是或否',
			'select' => '列表选择',
			'select-input' => '选择输入',
			'radio' => '单选框',
			'checkbox' => '多选框',
			'category' => '分类列表',
			'date' => '日期',
			'tblist' => '数据表列表',
			'searchlist' => '搜索模式',
			'inputmode' => '设置输入模式',
			'hidden' => '隐藏',
		);
	}
	if ($showarr['type'] == 'searchlist') {
		$showarr['type'] = 'select';
		$showarr['options'] = array(
			'' => '请选择',
			'=' => '等于',
			'>' => '大于',
			'!=' => '不等于',
			'<' => '小于',
			'like' => '包含'
		);
	}
	if ($showarr['type'] == 'tblist') {
		$showarr['type'] = 'select';
		$showarr['options'] = array_merge(array('' => '请选择'), gettablename());
	}
	if ($showarr['type'] == 'category') {
		$showarr['type'] = 'select';
		$model = new categories();
		$catlist = array();
		$catlist[''] = '请选择';
		$cats = $model->getcategory();
		foreach ($cats as $key => $var) {
			$catlist[$key] = $var['pre'] . $var['name'];
		}
		$showarr['options'] = $catlist;
	}
	$result = $showarr['value'];
	switch ($showarr['type']) {
		case 'file':
			$thetext = '<input name="' . $showarr['name'] . '" type="file" id="' . $showarr['name'] . '" size="' . $showarr['size'] . '" ' . $showarr['other'];
			if ($showarr['required']) {
				$thetext .= 'class="validate[required';
				if ($showarr['valid']) {
					$thetext .= $showarr['valid'];
				}
				$thetext .= ']"';
			}
			$thetext .= ' />';
			if ($showarr['required'])
				$thetext .= '<span style="font-weight: bold; color: #ff0000;">*</span>';
			$thetext .= "\n" . '<input name="' . $showarr['name'] . '_value" type="hidden" id="' . $showarr['name'] . '_value" value="' . $showarr['value'] . '" />';
			if (!empty($showarr['value'])) {
				$thetext .= "\n" . '<div id="' . $showarr['name'] . '_dv"><a href="' . $showarr['fileurl'] . '" target="_blank">' . $showarr['value'] . '</a>&nbsp;<a href="javascript:;" title="Delete" onclick="$(\'#' . $showarr['name'] . '_value\').val(\'\'); this.parentNode.parentNode.removeChild(this.parentNode);">删除</a></div>';
			}
			break;
		case 'upload':
			$result = '';
			if ($showarr['value']) {
				$isimg = false;
				if (substr($showarr['value'], -10) == '.thumb.jpg') {
					$isimg = true;
				} else {
					$up = new cmsUpload();
					$ext = $up->fileext($showarr['value']);
					if ($up->is_image_ext($ext)) {
						$isimg = true;
					}
				}
				if ($isimg) {
					$result = '<img alt="preview" src="' . A_URL . $showarr['value'] . '"';
					if ($showarr['width']) {
						$result .= ' width="' . $showarr['width'] . '" ';
					}
					if ($showarr['height']) {
						$result .= ' height="' . $showarr['height'] . '" ';
					} else {
						$result .= 'height="60" ';
					}
					$result .= '>';
				}
			}

			$count = count($showarr['values']);
			load::func('upload');
			if ($showarr['hash']) {
				$sql = "SELECT * FROM #__attachments WHERE hash='" . $showarr['hash'] . "' ORDER BY displayorder, aid DESC";
				DB::query($sql);
				while ($row = DB::fetch_array()) {
					$showarr['values'][] = $row;
					if (!$row['isimage'] && !$showarr['value']) {
						$ext = fileext($row['filepath']);
						$result .= '<li><a href="' . A_URL . $row['filepath'] . '" target="_blank">' . $row['filename'] . '.' . $ext . '(' . $row['filesize'] . ')' . '</a></li>';
					}
				}
			}
			$inserthtml = str_replace(array('\\\\', '\\'), '', getuploadinserthtml($showarr['values']));
			if (empty($showarr['allowtype']))
				$showarr['allowtype'] = '';
			$filesize = strtoupper(get_cfg_var('upload_max_filesize'));
			$filesize.= (substr($filesize, -1) != '0') ? 'B' : '';
			$thetext = "
<link href='static/js/jquery/uploadify-v3.1/uploadify.css' rel='stylesheet' type='text/css' />
<script type='text/javascript' >
$(function() {
    $('#uploadify').uploadify({
		'overrideEvents': ['onUploadStart'],
    	buttonClass   : 'btn',
		fileObjName   : 'uploadfile',
        height        : 20,
        width         : 80,
        swf           : 'static/js/jquery/uploadify-v3.1/uploadify.swf',
        uploader      : 'index.php?m=upload&a=upload&hash=" . $showarr['hash'] . "',
        fileSizeLimit : '" . $filesize . "',
        formData      : {hash: '" . $showarr['hash'] . "'},
		queueID       : 'fileQueue',
		auto          : false,
		buttonText    : '请选择文件',
		CompleteText  : '已完成',
		CancelledText : '已取消',
        multi         : true,
        'onUploadSuccess' : function(file, data, response) {
            //alert('The file ' + file.name + ' was successfully uploaded with a response of ' + response + ':' + data);
            $('#append_parent').append(data);
        },
        'onUploadError' : function(file, errorCode, errorMsg, errorString) {
			if(errorString!='Cancelled')
            alert('The file ' + file.name + ' could not be uploaded: ' + errorString);
        },
        'onUploadStart' : function(file) {
        	$('#theform').bind('submit', hasUpload);
            $('#startUpload').hide();
			$('#cancelUpload').show();
        },
        'onQueueComplete' : function(queueData) {
            $('#startUpload').hide();
			$('#cancelUpload').hide();
        	$('#theform').unbind('submit', hasUpload);
        },
        'onSelect' : function(file) {
        	$('#theform').bind('submit', hasUpload);
            $('#startUpload').show();
        },
        'onCancel' : function(file) {
			if(this.queueData.queueLength==1) {
				$('#startUpload').hide();
        		$('#theform').unbind('submit', hasUpload);
			}
        },
	});
});
function hasUpload(){
	return false;
}
	</script>
	";
			$thetext .= '
            <div id="uploadbox">
				<div id="fileQueue"></div>
				<input type="file" name="uploadify" id="uploadify" />
				<button class="btn" onclick="$(\'#uploadify\').uploadify(\'upload\', \'*\')" id="startUpload" style="display: none;">上传</button>
				<button class="btn" onclick="$(\'#uploadify\').uploadify(\'cancel\', \'*\')" id="cancelUpload" style="display: none;">取消</button>
				<input type="hidden" name="' . $showarr['name'] . '" value="' . $showarr['value'] . '">
				<input type="hidden" name="batchfile" value="' . $showarr['name'] . '">
                <p class="textmsg" id="divshowuploadmsg" style="display:block"></p>
             </div>';
			if ($showarr['hash']) {
				$thetext .= '<input type="hidden" id="hash" name="hash" value="' . $showarr['hash'] . '">';
			}

			$thetext .= '<div id="divshowupload" style="clear: both;">' . $inserthtml . '</div>';
			break;
		case 'uploadpic':
			if ($showarr['value'] && !$showarr['thumb']) {
				$showarr['thumb'] = $showarr['value'];
			}
			if ($showarr['thumb']) {
				if (substr($showarr['thumb'], 0, 7) != 'http://')
					$showarr['thumb'] = A_URL . $showarr['thumb'];
				$thetext = '<img alt="preview" src="' . $showarr['thumb'] . '"';

				if ($showarr['width']) {
					$thetext .= ' width="' . $showarr['width'] . '" ';
				}
				if ($showarr['height']) {
					$thetext .= ' height="' . $showarr['height'] . '" ';
				}
				$thetext .= '><br />';
			}
			$result = $thetext;
			$thetext .='<input type="file" name="' . $showarr['name'] . '" id="' . $showarr['name'] . '" size="15" >';
			break;
		case 'input':
			$thetext = '<input name="' . $showarr['name'] . '" type="text" id="' . $showarr['name'] . '" size="' . $showarr['size'] . '" value="' . $showarr['value'] . '" ' . $showarr['other'] . ' class="txt';
			if ($showarr['required']) {
				$thetext .= ' validate[required';
				if ($showarr['valid']) {
					$thetext .= $showarr['valid'];
				}
				$thetext .= ']';
			}
			$thetext .= '" />';
			if ($showarr['required'])
				$thetext .= '<span style="font-weight: bold; color: #ff0000;">*</span>';
			$result = $showarr['value'];
			break;
		case 'password':
			$thetext = '<input name="' . $showarr['name'] . '" type="password" id="' . $showarr['name'] . '" size="' . $showarr['size'] . '" value="' . $showarr['value'] . '"' . $showarr['other'] . ' class="txt';
			if ($showarr['required']) {
				$thetext .= ' validate[required';
				if ($showarr['valid']) {
					$thetext .= $showarr['valid'];
				}
				$thetext .= ']';
			}
			$thetext .= '" />';
			if ($showarr['required'])
				$thetext .= '<span style="font-weight: bold; color: #ff0000;">*</span>';
			$result = $showarr['value'];
			break;
		case 'input2':
			if (!isset($showarr['value'][0]))
				$showarr['value'][0] = '';
			if (!isset($showarr['value'][1]))
				$showarr['value'][1] = '';
			$thetext = '<input name="' . $showarr['name'] . '[]" type="text" id="' . $showarr['name'] . '0" size="' . $showarr['size'] . '" value="' . $showarr['value'][0] . '"' . $showarr['other'] . ' class="txt" />';
			$thetext .= ' ~ ';
			$thetext .= '<input name="' . $showarr['name'] . '[]" type="text" id="' . $showarr['name'] . '1" size="' . $showarr['size'] . '" value="' . $showarr['value'][1] . '"' . $showarr['other'] . ' class="txt" />';
			$result = $showarr['value'][0] . '~' . $showarr['value'][1];
			break;
		case 'editor':
			$text = '
					<script language="javascript" src="' . $control->settings['siteurl'] . '/static/js/editor/editor_function.js"></script>
					<textarea class="userData" name="content" id="jycms-ttHtmlEditor" style="height: 100%; width: 100%; display: none; border: 0px">' . $showarr['value'] . '</textarea>
					<iframe src="index.php?m=misc&a=editor" name="jycms-ifrHtmlEditor" id="jycms-ifrHtmlEditor" scrolling="no" border="0" frameborder="0" style="width:100%;height:400px;border: 1px solid #C5C5C5;"></iframe>
			';
			$htmltext .= '<tr><td colspan="3"><div id="fulledit" class="editerTextBox"><div id="' . $showarr['name'] . '" class="editerTextBox"></div></div>' . $text . '</td></tr>';
			$result = $showarr['value'];
			break;
		case 'textarea':
			$thetext = '<textarea name="' . $showarr['name'] . '" id="' . $showarr['name'] . '" style="width:98%;" rows="' . $showarr['rows'] . '"' . $showarr['other'] . ' class="txt';
			if ($showarr['required']) {
				$thetext .= ' validate[required';
				if ($showarr['valid']) {
					$thetext .= $showarr['valid'];
				}
				$thetext .= ']';
			}
			$thetext .= '">' . $showarr['value'] . '</textarea>';
			if ($showarr['required'])
				$thetext .= '<span style="font-weight: bold; color: #ff0000;">*</span>';
			$result = $showarr['value'];
			break;
		case 'select':
			$thetext = '<select name="' . $showarr['name'] . '" id="' . $showarr['name'] . '"' . $showarr['other'];
			if ($showarr['required']) {
				$thetext .= ' class="validate[required';
				if ($showarr['valid']) {
					$thetext .= $showarr['valid'];
				}
				$thetext .= ']" ';
			}
			$thetext .= '>' . "\n";
			foreach ($showarr['options'] as $tmpkey => $tmpvalue) {
				if ($showarr['opkey'])
					$tmpkey = $tmpvalue[$showarr['opkey']];
				if ($showarr['opvalue'])
					$tmpvalue = $tmpvalue[$showarr['opvalue']];
				if (strlen($showarr['value']) > 0 && $tmpkey == $showarr['value']) {
					$result = shtmlspecialchars($tmpvalue);
					$tmpselected = ' selected';
				} else {
					$tmpselected = '';
				}
				$thetext .= '<option value="' . $tmpkey . '"' . $tmpselected . '>' . shtmlspecialchars($tmpvalue) . '</option>' . "\n";
			}
			$thetext .= '</select>';
			if ($showarr['required'])
				$thetext .= '<span style="font-weight: bold; color: #ff0000;">*</span>';
			break;

		case 'select-input':
			$optionstr = '<select name="sl' . $showarr['name'] . '" onchange="changevalue(\'' . $showarr['name'] . '\', this.value)">';
			$optionstr .= '<option value="">请选择</option>';
			foreach ($showarr['options'] as $opkey => $opvalue) {
				if ($showarr['opkey'])
					$opkey = $opvalue[$showarr['opkey']];
				if ($showarr['opvalue']) {
					$opvalue = $opvalue[$showarr['opvalue']];
				}

				$optionstr .= '<option value="' . $opkey . '">' . $opvalue . '</option>';
			}
			$optionstr .= '</select>';
			$optionstr = str_replace('value="' . $showarr['value'] . '"', 'value="' . $showarr['value'] . '" selected', $optionstr);
			$thetext = '<input name="' . $showarr['name'] . '" type="text" id="' . $showarr['name'] . '" size="' . $showarr['size'] . '" value="' . $showarr['value'] . '" /> ';
			$thetext .= $optionstr;
			break;
		case 'yesorno':
			if (!isset($showarr['options']) || !$showarr['options'])
				$showarr['options'] = array(
					0 => '否',
					1 => '是'
				);
			$showarr['value'] = $showarr['value'];
		case 'radio':
			$thetext = '';
			//if(!strlen($showarr['value'])) $showarr['value'] = key($showarr['options']);
			foreach ($showarr['options'] as $tmpkey => $tmpvalue) {
				if (strlen($showarr['value']) > 0 && $tmpkey == $showarr['value']) {
					$result = $tmpvalue;
					$tmpchecked = ' checked';
				} else {
					$tmpchecked = '';
				}
				$thetext .= '<input name="' . $showarr['name'] . '" id="' . $showarr['name'] . random(6) . '" class="';
				if ($showarr['required']) {
					$thetext .= 'validate[required] ';
				}
				$thetext .= 'checkbox" type="radio" value="' . $tmpkey . '"' . $tmpchecked . $showarr['other'] . ' />' . $tmpvalue . '&nbsp;&nbsp;';
			}
			break;
		case 'checkbox':
			$thetext = '';
			$result = array();
			foreach ($showarr['options'] as $tmpkey => $tmpvalue) {
				$thetext .= '<div style="float: left; margin: 0 5px; display: block;"><input class="checkbox" name="' . $showarr['name'] . '[]" type="checkbox" value="' . $tmpkey . '"' . $showarr['other'] . ' />' . $tmpvalue . '</div>';
			}
			if (!empty($showarr['value'])) {
				if (is_array($showarr['value'])) {
					$showvaluearr = $showarr['value'];
				} else {
					$showvaluearr = explode(',', $showarr['value']);
				}
				foreach ($showvaluearr as $showvalue) {
					$showvalue = trim($showvalue);
					$thetext = str_replace('value="' . $showvalue . '"', 'value="' . $showvalue . '" checked', $thetext);
					if ($showvalue) {
						$result[] = $showarr['options'][$showvalue];
					}
				}
				$result = implode(',', $result);
			}
			break;
		case 'date':
		case 'time':
			$thetext = '<input name="' . $showarr['name'] . '" type="text" id="' . $showarr['name'] . '" value="' . $showarr['value'] . '"  class="txt dateinput';
			if ($showarr['required']) {
				$thetext .= ' validate[required';
				if ($showarr['valid']) {
					$thetext .= $showarr['valid'];
				}
				$thetext .= ']';
			}
			$thetext .= '" />';
			if ($showarr['required'])
				$thetext .= '<span style="font-weight: bold; color: #ff0000;">*</span>';
			break;
		case 'hidden':
			$result = $showarr['value'];
			$htmltext = '<tr><td colspan="2" style="display:none"><input name="' . $showarr['name'] . '" type="hidden" value="' . $showarr['value'] . '"' . $showarr['other'] . ' /></td></tr>';
			break;
		case 'title':
			$htmltext = '<tr><td colspan="3"><h3>' . $showarr['title'] . '</h3></td></tr>';
			break;
		case 'help':
			$htmltext = '<table cellspacing="2" cellpadding="2" class="helptable"><tr><td>' . $showarr['text'] . '</td></tr></table>';
			break;
		case 'label':
			if ($showarr['value']) {
				$thetext = $showarr['value'];
				unset($showarr['value']);
			} else {
				$htmltext = '<tr><th colspan="2">' . $showarr['title'] . '</th></tr>' . "\n";
			}
			break;
		case 'table-start':
			if ($showarr['name']) {
				$tblid = ' id="' . $showarr['name'] . '"';
			} else {
				$tblid = '';
			}
			if (isset($showarr['class'])) {
				$class = ' class="' . $showarr['class'] . '"';
			} else {
				$class = ' class="formtable"';
			}
			if (!$showarr['cellspacing']) {
				$showarr['cellspacing'] = 0;
			}
			$htmltext = '<center><table cellspacing="' . $showarr['cellspacing'] . '" cellpadding="0" width="100%" ' . $tblid . $class . '>' . "\n";
			break;
		case 'table-end':
			$htmltext = '</table></center>' . "\n";
			break;
		case 'div-start':
			if (empty($_ENV['_tmp_div_num'])) {
				$_ENV['_tmp_div_num'] = 1;
			} elseif ($_ENV['_tmp_div_num'] == 1) {
				$_ENV['_tmp_div_num'] = 2;
			} elseif ($_ENV['_tmp_div_num'] == 2) {
				$_ENV['_tmp_div_num'] = 3;
			} else {
				$_ENV['_tmp_div_num'] = 1;
			}
			$htmltext = '<div class="colorarea0' . $_ENV['_tmp_div_num'] . '">' . "\n";
			break;
		case 'div-end':
			$htmltext = '</div>' . "\n";
			break;
		case 'form-start':
			$htmltext = '<form method="post" name="' . $showarr['name'] . '" id="theform" action="' . $showarr['action'] . '" enctype="multipart/form-data" ' . $showarr['other'] . '>' . "\n" .
					'<input type="hidden" name="formhash" value="' . FORMHASH . '">' . "\n";
			break;
		case 'form-end':
			$htmltext = '</form>' . "\n";
			break;
		case 'submit':
			$thetext = '<center><input type="submit" id="issuance" name="' . $showarr['name'] . '" value="' . $showarr['value'] . '"' . $showarr['other'] . ' class="btn"></center>' . "\n";
			break;
		case 'reset':
			$thetext = '<input class="btn" type="reset" name="' . $showarr['name'] . '" value="' . $showarr['value'] . '">' . "\n";
			break;
		case 'text':
			$result = $thetext = $showarr['text'] . "\n";
		case 'eval':
			$htmltext = $showarr['text'] . "\n";
			break;
		default:
			$thetext = '';
			break;
	}
	if ($showarr['getvalue'])
		return $result;
	if (!empty($thetext)) {
		if (empty($showarr['display'])) {
			$tmpdisplay = '';
		} else {
			$tmpdisplay = ' style="display:none"';
		}
		if (empty($showarr['id'])) {
			$idname = 'tr_' . $showarr['name'];
		} else {
			$idname = $showarr['id'];
		}
		if ($showarr['title']) {
			$colspan = 1;
			$htmltext = '<tr>' . "\n" . '<th>' . $showarr['title'] . '</th>' . "\n";
		} else {
			$colspan = 2;
		}
		if ($showarr['note']) {
			$htmltext .= '<td align="left" colspan="' . $colspan . '">' . $thetext . '</td>' . "\n";
			$htmltext .= '<td align="left" class="fieldnote">' . $showarr['note'] . '</td>' . "\n" . '</tr>' . "\n";
		} else {
			$colspan++;
			if ($showarr['first']) {
				if ($showarr['colspan'] > 1) {
					$col = $showarr['colspan'];
				} else {
					$col = 1;
				}
				$colspan = 10;
				$htmltext .= '<td align="right" colspan="' . $col . '">' . $showarr['first'] . '</td>';
			}
			$htmltext .= '<td align="left" colspan="' . $colspan . '">' . $thetext . '</td>' . "\n" . '</tr>' . "\n";
		}
	}
	return $htmltext . "\n";
}

function processCustom($type = 'style') {
	global $_G;
	$css = '';
	if ($type == 'style') {
		if (isset($_G['custom']['style'])) {
			$styles = $_G['custom']['style'];
			foreach ($styles as $v) {
				$k = $v['id'];
				$css .= '<link rel="stylesheet" type="text/css" id="' . $k . '" href="' . $_G['siteurl'] . $v['src'] . '" />';
			}
		}
	} else {
		if (isset($_G['custom']['script'])) {
			$styles = $_G['custom']['script'];
			foreach ($styles as $v) {
				$k = $v['id'];
				$css .= '<script type="text/javascript" id="' . $k . '" src="'.$_G[siteurl].$v['src'].'"></script>';
			}
		}
	}
	echo $css;
}


//将数组中相同的值去掉,同时将后面的键名也忽略掉
function sarray_unique($array) {
	$newarray = array();
	if (!empty($array)&&is_array($array)) {
		$array = array_unique($array);
		foreach($array as $value) {
			$newarray[] = $value;
		}
	}
	return $newarray;
}

function processOptions($str, $mode = 'select') {
	if ($mode == 'select' || $mode == 'select-input')
		$options = array('' => '请选择');
	else
		$options = array();
	if (isset($str) && !is_array($str)) {
		if (substr($str, 0, 4) == 'SQL:') {
			$sql = substr($str, 4);
			DB::query($sql);
			while ($row = DB::fetch_array()) {
				$options[$row['value']] = $row['text'];
			}
		} elseif (substr($str, 0, 1) == '{') {
			$var = str_replace(array('{', '}'), '', $str);
			$vv = eval("return $var;");
			//pre($vv);exit;
			if (!is_array($vv)) {
				$vv = explode("\n", $vv);
				foreach ($vv as $k => $v) {
					$v = trim($v);
					list($key, $value) = explode('=', $v);
					if (!$value) {
						$value = $key;
						$key = $k;
					}
					$options[$key] = $value;
				}
			} else {
				//$options = array_merge($options, $vv);
				foreach ($vv as $k => $v) {
					$options[$k] = $v;
				}
			}
		} else {
			$nokey = 0;
			if(substr($str, 0, 1) == '@') {
				$str = substr($str, 1);
				$nokey = 1;
			}
			//$options = array();
			$vv = explode("\n", $str);
			foreach ($vv as $k => $v) {
				$v = trim($v);
				if ($v) {
					list($key, $value) = explode('=', $v);
					if (!$value) {
						$value = $key;
						$key = $nokey?$key:$k;
					}
					$options[$key] = $value;
				}
			}
		}
	} else {
		//pre($str, 1);
		//$options = array_merge($options, $str);
		foreach ($str as $k => $v) {
			$key = $k;
			$text = $v;
			if (is_array($v)) {
				if (isset($v['value']))
					$key = $v['value'];
				if (isset($v['text']))
					$text = $v['text'];
			}
			$options[$key] = $text;
		}
	}
	return $options;
}
